Get the name of the Focused element in C#

前端 未结 5 1034
甜味超标
甜味超标 2020-12-06 08:53

Is there a function in C# that can return the Name of the Focused element and display it in a text-box or something?

相关标签:
5条回答
  • 2020-12-06 09:08

    or you can do something like this...

      using System.ComponentModel;
      using System.Data;
      using System.Drawing;
      using System.Linq;
      using System.Text;
      using System.Windows.Forms;
      using System.Runtime.InteropServices;
    
    namespace WindowsFormsApplication1
    {
       public partial class Form1 : Form
       {
           public Form1()
           {
                InitializeComponent();            
           }
    
          private void button1_Click(object sender, EventArgs e)
          {
    
            MessageBox.Show(GetFocusControl());
          }
    
          [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.Winapi)]
          internal static extern IntPtr GetFocus();
    
          private string GetFocusControl()
          {
            Control focusControl = null;
            IntPtr focusHandle = GetFocus();
            if (focusHandle != IntPtr.Zero)
                focusControl = Control.FromHandle(focusHandle);
            if (focusControl.Name.ToString().Length == 0)
                return focusControl.Parent.Parent.Name.ToString();
            else
                return focusControl.Name.ToString();
          }
       }
     }
    
    0 讨论(0)
  • 2020-12-06 09:09

    Assuming WinForms, you can find the active (focused) control using the Form.ActiveControl property and get the name.

    Otherwise if this is a WPF project, you could use the FocusManager.GetFocusedElement() method to find it.

    0 讨论(0)
  • 2020-12-06 09:09

    Worked for me in c#.

    string name = ActiveForm.ActiveControl.Name;
    
    0 讨论(0)
  • 2020-12-06 09:19

    I just found that there's a way easier way of doing this if you're not using nested controls. You just reference

    Form1.ActiveControl.Name
    
    0 讨论(0)
  • 2020-12-06 09:20

    this function will return the index of Focused control in Form

        private int GetIndexFocusedControl()
        {
            int ind = -1;
            foreach (Control ctr in this.Controls)
            {
                if (ctr.Focused)
                {
                    ind = (int)this.Controls.IndexOf(ctr);
                }
            }
            return ind;
        }
    

    when you find the index of focused control you can access this control from control collection

    int indexFocused = GetIndexFocusedControl();
    textBox1.Text = this.Controls[indFocused].Name; // access the Name property of control
    
    0 讨论(0)
提交回复
热议问题