2011-10-02 160 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