2011-10-02 122 views

回答

6

,或者你可以做这样的事情......

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

这个函数会返回聚焦控制的索引表格

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 
+0

什么嵌套的控制? – Dyppl

+0

你可以迭代和找到集中控制在容器元素相同的方式作为面板等 – Serghei

+0

是的,但你的代码不会这样做 – Dyppl