簡體   English   中英

程序幾秒鍾無響應

[英]Program is unresponsive for a couple of seconds

我找到了一種方法來捕獲C#中的“ Print Screen按鈕。 當按下Alt + Print Screen彈出一個簡單的消息框,說明已按下了按鍵。 但是此后的幾秒鍾內無響應。 我不知道為什么會這樣。

這是我使用的代碼:

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        _hookID = SetHook(_proc);
        Application.Run(new Form1());
        UnhookWindowsHookEx(_hookID);  
    }

    /****************************************/
    private const int WH_KEYBOARD_LL = 13;
    //private const int WH_KEYBOARD_LL = 13;  
    private const int WM_KEYDOWN = 0x0100;
    private const int VK_F1 = 0x70;
    private static LowLevelKeyboardProc _proc = HookCallback;
    private static IntPtr _hookID = IntPtr.Zero;

    private static IntPtr SetHook(LowLevelKeyboardProc proc)
    {
        using (Process curProcess = Process.GetCurrentProcess())
        using (ProcessModule curModule = curProcess.MainModule)
        {
            return SetWindowsHookEx(WH_KEYBOARD_LL, proc,
                GetModuleHandle(curModule.ModuleName), 0);
        }
    }

    private delegate IntPtr LowLevelKeyboardProc(
        int nCode, IntPtr wParam, IntPtr lParam);

    private static IntPtr HookCallback(
        int nCode, IntPtr wParam, IntPtr lParam)
    {

        if (nCode >= 0)
        {
            Keys number = (Keys)Marshal.ReadInt32(lParam);
            if (number == Keys.PrintScreen)
            {
                if ((wParam == (IntPtr)260 && Keys.Alt == Control.ModifierKeys && number == Keys.PrintScreen))
                {
                    MessageBox.Show("You pressed alt+ print screen");
                }
            }

        }
        return CallNextHookEx(IntPtr.Zero, nCode, wParam, lParam);

    }

    [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); 
}

有誰知道它為什么掛在消息框后面?

在掛鈎回調完成執行之前,Windows無法調度下一個鍵盤消息。 顯然你希望使用MessageBox.Show(),該塊回調。 Windows在聲明您的代碼已損壞並禁用掛鈎之前忍受了幾秒鍾。

請改用Debug.Print()。

暫無
暫無

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

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