在C#中获取Focused元素的名称

C#中是否有一个函数可以返回聚焦元素的名称并将其显示在文本框中?

或者你可以做这样的事……

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

假设WinForms,您可以使用Form.ActiveControl属性找到活动(聚焦)控件并获取名称。

否则,如果这是一个WPF项目,您可以使用FocusManager.GetFocusedElement()方法来查找它。

此函数将返回Form中聚焦控件的索引

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

当您找到聚焦控件的索引时,您可以从控件集合中访问此控件

 int indexFocused = GetIndexFocusedControl(); textBox1.Text = this.Controls[indFocused].Name; // access the Name property of control