简体   繁体   中英

Get the name of the Focused element in C#

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

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.

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

在 c# 中为我工作。

string name = ActiveForm.ActiveControl.Name;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM