在不聚焦窗口的情况下捕获键 [英] Capturing a key without focusing the window

查看:133
本文介绍了在不聚焦窗口的情况下捕获键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应用程序,该应用程序始终检查是否按下了 F12 之类的键.它不需要聚焦在应用程序的主窗口中.我尝试了这段代码:

I have a application that always checks if a key like F12 is pressed. It doesn't need to have in focus of my main window of my app. I tried this code:

public int a = 1;
    // DLL libraries used to manage hotkeys
    [DllImport("user32.dll")]
    public static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, int vlc);
    [DllImport("user32.dll")]
    public static extern bool UnregisterHotKey(IntPtr hWnd, int id);

    const int MYACTION_HOTKEY_ID = 1;

    public Form1()
    {
        InitializeComponent();
        // Modifier keys codes: Alt = 1, Ctrl = 2, Shift = 4, Win = 8
        // Compute the addition of each combination of the keys you want to be pressed
        // ALT+CTRL = 1 + 2 = 3 , CTRL+SHIFT = 2 + 4 = 6...
        RegisterHotKey(this.Handle, MYACTION_HOTKEY_ID, 0, (int) Keys.F12);
    }

    protected override void WndProc(ref Message m)
    {
        if (m.Msg == 0x0312 && m.WParam.ToInt32() == MYACTION_HOTKEY_ID)
        {

            a++;
            MessageBox.Show(a.ToString());
        }
        base.WndProc(ref m);
    }

我在此行RegisterHotKey(this.Handle, MYACTION_HOTKEY_ID, 0, (int) Keys.F12);上放置了0,以便仅在按下 F12 时才会捕获.

I put 0 to this line RegisterHotKey(this.Handle, MYACTION_HOTKEY_ID, 0, (int) Keys.F12); so that only if F12 is pressed it will capture.

但是没有用.我该如何解决?

But it didn't work. How can I solve this?

在这里我听不懂以下几行:

Here I couldn't understand some lines like:

const int MYACTION_HOTKEY_ID = 1;
m.Msg == 0x0312 && m.WParam.ToInt32() == MYACTION_HOTKEY_ID
base.WndProc(ref m);

有人可以帮助我理解这些内容吗?

Can anyone help me to understand these lines?

推荐答案

您的代码没有错.但这在这里不起作用,因为保留了 F12 键,您可以尝试使用其他键,例如 F10 F11 等.

Your code has no wrong . But it doesn't work here because the F12 key is reserved you may try with another key like F10, F11 etc .

这篇关于在不聚焦窗口的情况下捕获键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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