ProcessCmdKey-等待KeyUp吗? [英] ProcessCmdKey - wait for KeyUp?

查看:160
本文介绍了ProcessCmdKey-等待KeyUp吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在WinForms应用程序中遇到以下问题. 我正在尝试实现热键,并且只要控件处于活动状态,无论焦点是否位于该控件内的文本框上,我都需要处理键消息.

I'm having the following issue in a WinForms app. I'm trying to implement Hotkeys and I need to process Key messages whenever the control is active, no matter if the focus is on a textbox within that control, etc.

重写ProcessCmdKey可以很好地完成此工作,并且完全可以实现我想要的功能,但有一个例外:

Overriding ProcessCmdKey works beautifully for this and does exactly what I want with one exception:

如果用户按下某个键并保持按下状态,则ProcessCmdKey会继续触发WM_KEYDOWN事件.

If a user presses a key and keeps it pressed, ProcessCmdKey keeps triggering WM_KEYDOWN events.

但是,我要实现的是用户必须再次释放按钮才能触发另一个热键操作(因此,如果有人坐在键盘上,不会导致连续的热键事件).
但是,我找不到在何处捕获WM_KEYUP事件,因此可以设置一个标志是否应再次处理ProcessCmdKey消息?

However, what I want to achieve is that the user has to release the button again before another hotkey action would trigger (so, if someone sits on the keyboard it would not cause continuous hotkey events).
However, I can't find where to catch WM_KEYUP events, so I can set a flag if it should process ProcessCmdKey messages again?

任何人都可以在这里帮忙吗?

Anyone can help out here?

谢谢

汤姆

推荐答案

我认为这很简单,只需查看密钥的重复计数即可.如果使用修饰符,则无法使用.您还需要查看密钥,这需要实现IMessageFilter.这可行:

I thought it'd be easy, just look at the key's repeat count. Didn't work though if modifiers are used. You'll need to see the key go up as well, that requires implementing IMessageFilter. This worked:

public partial class Form1 : Form, IMessageFilter {
    public Form1()  {
        InitializeComponent();
        Application.AddMessageFilter(this);
        this.FormClosed += (s, e) => Application.RemoveMessageFilter(this);
    }
    bool mRepeating;
    protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
        if (keyData == (Keys.Control | Keys.F) && !mRepeating) {
            mRepeating = true;
            Console.WriteLine("What the Ctrl+F?");
            return true;
        }
        return base.ProcessCmdKey(ref msg, keyData);
    }
    public bool PreFilterMessage(ref Message m) {
        if (m.Msg == 0x101) mRepeating = false;
        return false;
    }
}

这篇关于ProcessCmdKey-等待KeyUp吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆