Jon*_*n B 11 .net c# event-handling winforms
我需要在表单中捕获KeyUp事件(以切换"全屏模式").这是我正在做的事情:
protected override void OnKeyUp(KeyEventArgs e)
{
base.OnKeyUp(e);
if (e.KeyCode == Keys.F12) this.ToggleFullScreen();
}
private void ToggleFullScreen()
{
// Snazzy code goes here
}
Run Code Online (Sandbox Code Playgroud)
这样工作正常,除非窗体上的控件具有焦点.在那种情况下,我根本没有得到这个事件(也试过OnKeyDown - 也没有运气).
我可以从子控件处理KeyUp事件,但是表单上的控件是动态生成的,并且可能有很多控件 - 每个控件都有很多自己的子控件.
有没有办法做到这一点,而不为屏幕上的每个控件生成事件处理程序(我当然可以使用递归函数)?
its*_*att 12
将表单的KeyPreview设置为true,您可以拦截KeyUp事件.
在我的测试应用中,我做了类似这样的事情:
this.KeyPreview = true;
.
.
.
private void button1_KeyUp(object sender, KeyEventArgs e)
{
Trace.WriteLine("button key up");
}
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
Trace.WriteLine("form key up");
e.Handled = true;
}
Run Code Online (Sandbox Code Playgroud)
它将转储表单跟踪行,处理该键并且不会调用按钮处理程序.当然,您可以不处理事件(不执行e.Handled = true),然后也会调用按钮处理程序.
您是否尝试过在表单上全局处理事件?
protected override bool ProcessCmdKey(ref Message msg, Keys e)
{
if (e.KeyCode == Keys.F12)
{
this.ToggleFullScreen();
return true; //marks command as handled
}
return base.ProcessCmdKey(ref msg, e); // Resend To Base Function
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6848 次 |
| 最近记录: |