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

  • 相关阅读:
    Android Facebook分享功能实现
    Facebook KeyHash生成方法
    Android 版 Facebook 登录
    在Android App中集成Google登录
    Android 应用程序集成FaceBook 登录及二次封装
    Android Facebook和Twitter登录和分享完整版
    android开发之自定义圆形ImagView
    Okhttp、Volley和Gson的简单介绍和配合使用
    Android并发编程
    重要的ui组件——Behavior
  • 原文地址:https://www.cnblogs.com/2018/p/1893891.html
Copyright © 2020-2023  润新知