获取C#中Focused元素的名称#
答
,或者你可以做这样的事情......
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();
}
}
}
答
这个函数会返回聚焦控制的索引表格
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
答
假设的WinForms,你可以使用Form.ActiveControl
属性找到活动(聚焦)控件并获取名称。
否则,如果这是一个WPF项目,您可以使用FocusManager.GetFocusedElement()
方法找到它。
什么嵌套的控制? – Dyppl
你可以迭代和找到集中控制在容器元素相同的方式作为面板等 – Serghei
是的,但你的代码不会这样做 – Dyppl