开发者

Get the name of the Focused element in C#

Is there a function in C# t开发者_开发知识库hat can return the Name of the Focused element and display it in a text-box or something?


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();
      }
   }
 }


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.


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


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


Worked for me in c#.

string name = ActiveForm.ActiveControl.Name;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜