簡體   English   中英

如何在 C# 中制作全局鍵盤掛鈎

[英]How to make a global keyboard hook in C#

如何在 C# 中為 Electron.NET 應用程序制作全局鍵盤掛鈎? 我相信只要它在控制台應用程序中工作,它就應該在 Electron.Net 應用程序中正常工作。

我為這個問題做了一個“解決方案”,但它往往會消耗大量的 CPU(7-10%)。 如果沒有其他選擇,也許有人能夠以某種方式使其真正有效:

using System;
using System.Runtime.InteropServices;
using System.Threading;

[DllImport("User32.dll")]
public static extern short GetAsyncKeyState(int vKey);

// Other VKey codes: https://docs.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes
public enum VKeys {
    LBUTTON = 0x01,     // Left mouse button
    RBUTTON = 0x02,     // Right mouse button
    KEY_0 = 0x30,       // 0 key
    KEY_1 = 0x31,       // 1 key
    KEY_2 = 0x32,       // 2 key
    KEY_3 = 0x33,       // 3 key
    KEY_4 = 0x34,       // 4 key
    KEY_5 = 0x35,       // 5 key
    KEY_6 = 0x36,       // 6 key
    KEY_7 = 0x37,       // 7 key
    KEY_8 = 0x38,       // 8 key
    KEY_9 = 0x39        // 9 key
}

public void Start()
{
    Thread HookThread = new Thread(delegate ()
    {
        var keys = Enum.GetValues(typeof(VKeys));

        while (true)
        {
            foreach (int key in keys)
            {
                var ks = GetAsyncKeyState(key);

                if (ks < 0)
                {
                    Console.WriteLine($"pressed {key}");
                    //Thread.Sleep(100);
                }

                //Thread.Sleep(1); // Even sleeping for '1ms' will delay it too much
            }
        }
    });

    HookThread.Start();
}

我發現的很多東西只有在我使用 WinForms 或 WPF 時才有效。

編輯:

我嘗試了 hanabanashiku 的這個答案,以及我在網上找到的許多其他答案,但它們似乎都只是滯后於鍵盤輸入,而且它們的回調函數似乎永遠不會被調用。

I decided to write the keyboard hook in C++, compile as a DLL and then reference that DLL in my C# code to hopefully make a keyboard hook that functioned properly and didn't cause any noticeable input lag, but that didn't work either.

The keyboard hook ran perfectly when run as an.exe in C++, but when I compiled it as a DLL and ran it in C# it caused the same issue as before - a lot of input lag and the callback function seemingly not being called.

如果有人想嘗試,這是代碼:

鍵盤鈎子.cpp

#include "KeyboardHook.h"
#include <iostream>

#define __event void KeyDown(int key), KeyUp(int key);

using namespace Hooks;

void KeyDown(int key)
{
    std::cout << "KeyDown\n";
}

void KeyUp(int key)
{
    std::cout << "KeyUp\n";
}

LRESULT CALLBACK KeyboardProc(int nCode, WPARAM wParam, LPARAM lParam)
{
    if (nCode == HC_ACTION)
    {
        PKBDLLHOOKSTRUCT p = (PKBDLLHOOKSTRUCT)lParam;

        switch (wParam)
        {
            case WM_KEYDOWN:
            case WM_SYSKEYDOWN:
                KeyDown(p->vkCode);
                break;
            case WM_KEYUP:
            case WM_SYSKEYUP:
                KeyUp(p->vkCode);
                break;
        }
    }

    // Not processing keys so always return CallNextHookEx
    return(CallNextHookEx(NULL, nCode, wParam, lParam));
}

void KeyboardHook::Install() {
    // Install keyboard hook
    keyboardHook = SetWindowsHookEx(WH_KEYBOARD_LL, KeyboardProc, 0, 0);
    std::cout << "Installed\n";
}

void KeyboardHook::Uninstall() {
    // Unhook keyboard hook
    UnhookWindowsHookEx(keyboardHook);
}

鍵盤鈎子.h

#include <Windows.h>

HHOOK keyboardHook;

namespace Hooks 
{
    class KeyboardHook
    {
    public:
        __declspec(dllexport) void Install();
        __declspec(dllexport) void Uninstall();
    };
}

程序.cs

using System;
using System.Runtime.InteropServices;

namespace HelloMyNameIsSpindiNiceToMeetYou
{
    class Program
    {
        private const string hooksPath = @"C:\Path\To\Hooks.dll";

        // If EntryPoint doesn't work, yours might be different
        // https://docs.microsoft.com/en-us/dotnet/framework/interop/identifying-functions-in-dlls
        //
        // "For example, you can use dumpbin /exports Hooks.dll [...] to obtain function names." 
        // you need to be in the folder with the dll for above to work in Command Prompt for VS
        [DllImport(hooksPath, EntryPoint = "?Install@KeyboardHook@Hooks@@QEAAXXZ", CallingConvention = CallingConvention.Cdecl)]
        private extern static void Install();

        static void Main(string[] args)
        {
            Install();

            // keep console app running
            while (true)
            {
                continue;
            }

            // or keep it running with this
            // Console.ReadKey();
        }
    }
}

我現在正在一個 electron.net 應用程序之外測試這些東西,只是在一個控制台應用程序中,事情仍然無法正常工作。 我發現的一切都導致回到使用我無法使用的 winforms。

Electron 有一種內置創建全局快捷方式的方法,您只需稍微調整語法即可使用 Electron.Net,您可以搜索存儲以找出 ZC1C425268E68385D1AB5074C17A941F

注冊快捷方式:

Electron.GlobalShortcut.Register("CommandOrControl+X", () =>
{
    Console.WriteLine("CommandOrControl+X pressed");
});

取消注冊快捷方式:

// Unregister specific shortcut
Electron.GlobalShortcut.Unregister("CommandOrControl+X");

// Unregister all shortcuts
Electron.GlobalShortcut.UnregisterAll();

您的解決方案使用了大量的計算能力,因為每次循環重復時,它都會對 Windows API 進行 11 次調用。 為了更有效地完成此操作,您將需要添加一個鍵盤掛鈎 一個簡單的解決方案如下所示。

[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern IntPtr SetWindowsHookEx(int idHook, LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);

[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool UnhookWindowsHookEx(IntPtr hhk);

[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);

[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr GetModuleHandle(string lpModuleName);

private const int WH_KEYBOARD_LL = 13;
private const int WM_KEYDOWN = 0x0100;
private delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);


private static InPtr hook_ = IntPtr.Zero;
private static LowLevelHookProc _proc = KeyboardProc;

public void Start() {
    using (var process = Process.GetCurrentProcess())
        using (var module = process.MainModule)
        {
            _hook = SetWindowsHookEx(WH_KEYBOARD_LL, _proc,
                GetModuleHandle(module.ModuleName), 0);
        }

private static IntPtr KeyboardProc(int nCode, IntPtr wParam, IntPtr lParam)
    {
        if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN) {
            switch(nCode) {
                 // Look for keys
            }
        }

        return CallNextHookEx(_hookID, nCode, wParam, lParam);
    }

每次按下一個鍵時都會觸發回調 function。 只需查找您要查詢的虛擬鍵。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM