Csharp/C#教程:在C#中获取Focused元素的名称分享


在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; } 

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

上述就是C#学习教程:在C#中获取Focused元素的名称分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

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

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1016753.html

(0)
上一篇 2021年12月31日
下一篇 2021年12月31日

精彩推荐