1、設置整個窗體keydown事件的時候,要設置keyPreview=true;
2、獲取當前擁有焦點的控件:
關於這個問題,自己也是糾結死了,在網上搜了好多相關的問題答案,搜出的結果是:
//API聲明:獲取當前焦點控件句柄
[DllImport("user32.dll")]
public static extern int GetFocus();
///獲取 當前擁有焦點的控件
private string GetFocusedControl()
{
string focusedControl = null;
IntPtr handle = (IntPtr)GetFocus();
if (handle == null)
this.FindForm().KeyPreview = true;
else
{
Control c = Control.FromHandle(handle);//這就是
focusedControl =
c.Parent.TopLevelControl.Name.ToString();
}
return focusedControl;
}
方法本身也沒有問題,但是我的頁面上用的當前控件剛好是引用的用戶控件,使用此方法得出的結果是獲得了原始的控件名字,不能用了。最好的獲得方法就是: Control ctl = this.ActiveControl;
這個ctl.name,就是你要獲取的當前焦點所在的控件了~