zoukankan      html  css  js  c++  java
  • VSTO应用程序中加入键盘钩子

    在VSTO应用程序中有时为了处理一些快捷按键操作等实现一些特殊的功能,此时需要对键盘进行挂钩,此时使用P/Invoke函数实现,参考如下:

    VSTO加载和卸载时进行钩子的初始化和卸载

    代码
    KeyboardHook hook;
    private void ThisAddIn_Startup(object sender, System.EventArgs e)
    {
    hook
    = new KeyboardHook();
    hook.InitHook();
    }

    private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
    {
    hook.UnHook();
    }
    }
    //钩子具体处理逻辑是:
    class KeyboardHook
    {
    #region (invokestuff)
    [DllImport(
    "kernel32.dll")]
    static extern uint GetCurrentThreadId();
    [DllImport(
    "user32.dll")]
    static extern IntPtr SetWindowsHookEx(int code, HookProcKeyboard func, IntPtr hInstance, uint threadID);
    [DllImport(
    "user32.dll")]
    static extern bool UnhookWindowsHookEx(IntPtr hhk);
    [DllImport(
    "user32.dll")]
    static extern int CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);
    #endregion

    #region constans
    private const int WH_KEYBOARD = 2;
    private const int HC_ACTION = 0;
    #endregion

    delegate int HookProcKeyboard(int code, IntPtr wParam, IntPtr lParam);
    private HookProcKeyboard KeyboardProcDelegate = null;
    private IntPtr khook;
    bool doing = false;

    public void InitHook()
    {
    uint id = GetCurrentThreadId();
    //init the keyboard hook with the thread id of the Visual Studio IDE
    this.KeyboardProcDelegate = new HookProcKeyboard(this.KeyboardProc);
    khook
    = SetWindowsHookEx(WH_KEYBOARD, this.KeyboardProcDelegate, IntPtr.Zero, id);
    }

    public void UnHook()
    {
    if (khook != IntPtr.Zero)
    {
    UnhookWindowsHookEx(khook);
    }
    }

    private int KeyboardProc(int code, IntPtr wParam, IntPtr lParam)
    {
    try
    {
    if (code != HC_ACTION)
    {
    return CallNextHookEx(khook, code, wParam, lParam);
    }

    if ((int)wParam == (int)Keys.Z && ((int)lParam & (int)Keys.Alt) != 0)
    {
    if (!doing)
    {
    doing
    = true;
    MessageBox.Show(
    "Captured");
    doing
    = false;
    }
    }
    }
    catch
    {
    }

    return CallNextHookEx(khook, code, wParam, lParam);
    }
    }

  • 相关阅读:
    三级联动下拉菜单1
    IP地址查询接口及调用方法
    实现简单的网页拖拽效果
    [转载]PHP如何获取客户端真实IP
    mysql(二)连接查询
    php exec 执行php脚本
    PHP-将某一目录下文件压缩成zip格式
    从读书时代想我的程序之路
    Github上建立自己的网站
    小米手机购买程序,如果是我,我会怎么写
  • 原文地址:https://www.cnblogs.com/2018/p/1893891.html
Copyright © 2011-2022 走看看