簡體   English   中英

在 C# 中獲取 Focused 元素的名稱

[英]Get the name of the Focused element in C#

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()方法來查找它。

我剛剛發現,如果您不使用嵌套控件,則有一種更簡單的方法可以做到這一點。 你只是參考

Form1.ActiveControl.Name

在 c# 中為我工作。

string name = ActiveForm.ActiveControl.Name;

此函數將返回 Form 中 Focused 控件的索引

    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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM