在WinForms應用程序中找到集中控件的首選方法是什么?找到當前在WinForms中接收用戶(鍵盤)輸入的控件的首選/最簡單方法是什么?到目前為止,我已經提出以下建議:public static Control FindFocusedControl(Control control){
var container = control as ContainerControl;
return (null != container ? FindFocusedControl(container.ActiveControl)
: control);}從表單中,這可以簡單地稱為(在.NET 3.5+中甚至可以將其定義為表單上的擴展方法) -var focused = FindFocusedControl(this);這個合適嗎?是否有我應該使用的內置方法?請注意,使用層次結構時,單次調用ActiveControl是不夠的。想像:Form
TableLayoutPanel
FlowLayoutPanel
TextBox (focused)(formInstance).ActiveControl將返回對TableLayoutPanel的引用,而不是TextBox(因為ActiveControl似乎只是在控制樹中返回直接活動的子節點,而我正在尋找葉子控件)。
3 回答

慕姐4208626
TA貢獻1852條經驗 獲得超7個贊
如果您已經對Windows API進行了其他調用,那么使用Peters解決方案沒有任何害處。但是我理解你對它的擔憂,并且傾向于使用與你類似的解決方案,只使用Framework功能。畢竟,性能差異(如果有的話)不應該很重要。
我會采取非遞歸的方法:
public static Control FindFocusedControl(Control control){ var container = control as IContainerControl; while (container != null) { control = container.ActiveControl; container = control as IContainerControl; } return control;}
- 3 回答
- 0 關注
- 558 瀏覽
添加回答
舉報
0/150
提交
取消