简体   繁体   English

Office Addin 2013中的C#全局键盘挂钩

[英]C# Global keyboard hook in Office Addin 2013

I encounter a problem to make my Office Addin works with my global keyboard on Powerpoint 2013 but not on the previous versions (2007 and 2010). 我在Powerpoint 2013上使我的Office外接程序与全局键盘一起工作时遇到问题,而在以前的版本(2007和2010)上却没有。
I do not get any exception but it seems that the OnKeyDown event is never triggered on Powerpoint 2013, and I don't know why. 我没有任何异常,但似乎OnKeyDown事件从未在Powerpoint 2013上触发,我也不知道为什么。

I get the same problems on all versions of Windows (XP, 7, 8 & 8.1), on 32 & 64 bits environments. 在32和64位环境中,在所有版本的Windows(XP,7、8和8.1)上,我都会遇到相同的问题。 The version of Microsoft Office is 32 bits. Microsoft Office的版本是32位。

Here is a code sample : 这是一个代码示例:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using PowerPoint = Microsoft.Office.Interop.PowerPoint;
using Office = Microsoft.Office.Core;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Diagnostics;

namespace testHook
{
    public partial class ThisAddIn
    {
        Hook hook;

        private void ThisAddIn_Startup(object sender, System.EventArgs e)
        {
            hook = new Hook(Hook.HookType.KeyBoard, Hook.HookVisibility.Global);
            hook.OnKeyDown += new KeyEventHandler(hook_OnKeyDown);
            hook.Start();
        }

        void hook_OnKeyDown(object sender, KeyEventArgs e)
        {
            MessageBox.Show(e.KeyCode.ToString());
        }

        private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
        {
            hook.Stop();
            hook = null;
        }

        #region VSTO generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InternalStartup()
        {
            this.Startup += new System.EventHandler(ThisAddIn_Startup);
            this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
        }

        #endregion

    class Hook
    {
        private IntPtr m_Hook = (IntPtr)0;
        private HookVisibility m_Visibility;
        private HookType m_HookType;
        private HookProc m_Proc;

        public enum HookType { KeyBoard };
        public enum KeyBoardEventType { KeyDown, KeyUp, SysKeyDown, SysKeyUp, KeyShift, KeyCapital, NumLock };
        public enum HookVisibility { Global, Local };

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

        private KeyPressEventHandler m_onKeyPress;
        private KeyEventHandler m_onKeyUp;
        private KeyEventHandler m_onKeyDown;

        public event KeyPressEventHandler OnKeyPress
        {
            add
            {
                m_onKeyPress += value;
            }
            remove
            {
                m_onKeyPress -= value;
            }
        }
        public event KeyEventHandler OnKeyUp
        {
            add
            {
                m_onKeyUp += value;
            }
            remove
            {
                m_onKeyUp -= value;
            }
        }
        public event KeyEventHandler OnKeyDown
        {
            add
            {
                m_onKeyDown += value;
            }
            remove
            {
                m_onKeyDown -= value;
            }
        }

        #region DLLImport

        [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
        private static extern IntPtr SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hmod, int dwThreadId);

        [DllImport("user32.dll")]
        private static extern IntPtr CallNextHookEx(IntPtr hHook, int nCode, IntPtr wParam, IntPtr lParam);

        [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
        private static extern bool UnhookWindowsHookEx(IntPtr hHook);

        [DllImport("Kernel32.dll", SetLastError = true)]
        private static extern IntPtr GetModuleHandle(IntPtr lpModuleName);

        [DllImport("Kernel32.dll", SetLastError = true)]
        private static extern IntPtr GetModuleHandle(String lpModuleName);

        [DllImport("Kernel32.dll")]
        private static extern IntPtr GetCurrentThreadId();

        [DllImport("user32")]
        private static extern int ToAscii(int uVirtKey, int uScanCode, byte[] lpbKeyState, byte[] lpwTransKey, int fuState);

        [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
        private static extern short GetKeyState(int vKey);

        [DllImport("user32")]
        private static extern int GetKeyboardState(byte[] pbKeyState);

        #endregion

        [StructLayout(LayoutKind.Sequential)]
        private class KeyboardHookStruct
        {
            public int vkCode;
            public int scanCode;
            public int flags;
            public int time;
            public int dwExtraInfo;
        }

        public Hook(HookType H, HookVisibility H2)
        {
            m_HookType = H;
            m_Visibility = H2;
        }

        public bool Start()
        {
            if (m_HookType == HookType.KeyBoard)
                m_Proc = new HookProc(KeyProc);

            if (m_Visibility == HookVisibility.Global)
                m_Hook = SetWindowsHookEx(getHookType(m_HookType, m_Visibility), m_Proc, GetModuleHandle(Process.GetCurrentProcess().MainModule.ModuleName), 0);

            else if (m_Visibility == HookVisibility.Local)
                m_Hook = SetWindowsHookEx(getHookType(m_HookType, m_Visibility), m_Proc, GetModuleHandle((IntPtr)0), (int)GetCurrentThreadId());

            if (m_Hook == (IntPtr)0)
                return false;

            return true;
        }

        public bool Stop()
        {
            return UnhookWindowsHookEx(m_Hook);
        }

        private int getHookType(HookType H, HookVisibility V)
        {
            if (H == HookType.KeyBoard && V == HookVisibility.Local)
                return 2;
            if (H == HookType.KeyBoard && V == HookVisibility.Global)
                return 13;

            else return -1;
        }

        private int getKeyBoardEventType(KeyBoardEventType K)
        {
            if (K == KeyBoardEventType.KeyDown)
                return 0x100;
            if (K == KeyBoardEventType.KeyUp)
                return 0x101;
            if (K == KeyBoardEventType.SysKeyDown)
                return 0x104;
            if (K == KeyBoardEventType.SysKeyUp)
                return 0x105;
            if (K == KeyBoardEventType.KeyShift)
                return 0x10;
            if (K == KeyBoardEventType.KeyCapital)
                return 0x14;
            if (K == KeyBoardEventType.NumLock)
                return 0x90;

            else return -1;
        }

        private IntPtr KeyProc(int nCode, int wParam, IntPtr lParam)
        {
            bool handled = false;
            if ((nCode >= 0) && (m_onKeyDown != null || m_onKeyUp != null || m_onKeyPress != null))
            {
                KeyboardHookStruct MyKeyboardHookStruct = (KeyboardHookStruct)Marshal.PtrToStructure(lParam, typeof(KeyboardHookStruct));

                if (m_onKeyDown != null && (wParam == 0x100 || wParam == 0x104))
                {
                    Keys keyData = (Keys)MyKeyboardHookStruct.vkCode;
                    KeyEventArgs e = new KeyEventArgs(keyData);
                    m_onKeyDown(this, e);
                    handled = handled || e.Handled;
                }

                if (m_onKeyPress != null && wParam == 0x100)
                {
                    bool isShift = ((GetKeyState(0x10) & 0x80) == 0x80 ? true : false);
                    bool isCapslock = (GetKeyState(0x14) != 0 ? true : false);

                    byte[] keyState = new byte[256];
                    GetKeyboardState(keyState);
                    byte[] inBuffer = new byte[2];
                    if (ToAscii(MyKeyboardHookStruct.vkCode, MyKeyboardHookStruct.scanCode, keyState, inBuffer, MyKeyboardHookStruct.flags) == 1)
                    {
                        char key = (char)inBuffer[0];
                        if ((isCapslock ^ isShift) && Char.IsLetter(key))
                            key = Char.ToUpper(key);
                        KeyPressEventArgs e = new KeyPressEventArgs(key);
                        m_onKeyPress(this, e);
                        handled = handled || e.Handled;
                    }
                }

                if (m_onKeyUp != null && (wParam == 0x101 || wParam == 0x105))
                {
                    Keys keyData = (Keys)MyKeyboardHookStruct.vkCode;
                    KeyEventArgs e = new KeyEventArgs(keyData);
                    m_onKeyUp(this, e);
                    handled = handled || e.Handled;
                }
            }

            if (handled)
                return (IntPtr)1;
            else
                return CallNextHookEx(m_Hook, nCode, (IntPtr)wParam, (IntPtr)lParam);
        }
    }
}

My application need to fire events during the slideshow because I have some others windows which are displayed during the presentation, and I have to update them according to the keys that the user presses. 我的应用程序需要在幻灯片放映期间触发事件,因为在演示过程中还显示了一些其他窗口,因此我必须根据用户按下的键来更新它们。 I have tried a lot of solutions but the hook is the only one that can do perfectly the job. 我尝试了很多解决方案,但是钩子是唯一可以完美完成工作的解决方案。

I tried too a local keyboard hook instead of a global one. 我也尝试使用本地键盘挂钩而不是全局键盘挂钩。 I actually think that it is the only way to make it works because it is a bug from Microsoft, and not from the code. 实际上,我认为这是使它起作用的唯一方法,因为它是Microsoft的错误,而不是代码的错误。 However, I can't make the local one works properly on any version of Powerpoint. 但是,我无法使本地版本在任何版本的Powerpoint上都能正常工作。

The issue is not Powerpoint specific, it occurs with any Office product. 此问题不是Powerpoint特有的,任何Office产品都会出现。 I'm working on a Outlook addin and fancing this problem. 我正在研究Outlook插件并解决了这个问题。 It has been reported (without any answer unfortunely) to Microsoft: https://social.msdn.microsoft.com/Forums/office/en-US/93d08ccc-9e77-4f72-9c51-477468d89681/keyboardhook-will-not-work-in-word-2013?forum=worddev 已向Microsoft报告(没有任何不幸的答案): https : //social.msdn.microsoft.com/Forums/office/en-US/93d08ccc-9e77-4f72-9c51-477468d89681/keyboardhook-will-not-work -in-字2013?论坛= worddev

I have been able to make a "workaround": i have register a Global Hook AND a Local one ("Thread"). 我已经能够做出“解决方法”:我已经注册了一个全局钩子和一个本地钩子(“线程”)。 It works, but the keyProc is called "weirdly" when it's local, not respecting documented parameters: - wParam is not one of WM_*, but contains directly the vkCode - lParam cannot be accessed (AccessViolation) As I understood, it's because some "TranslateMessage" processing. 它可以工作,但是keyProc在本地时会被称为“古怪”,不遵守记录的参数:-wParam不是WM_ *之一,而是直接包含vkCode-无法访问lParam(AccessViolation)据我了解,这是因为某些“ TranslateMessage”处理。

I have also adapted your code to be able to catch ALT combination. 我还对您的代码进行了修改,使其能够捕获ALT组合。

    private bool wParamAlt;

    private IntPtr KeyProc(int nCode, int wParam, IntPtr lParam)
    {
        bool handled = false;
        if ((nCode == 0) && (m_onKeyDown != null || m_onKeyUp != null || m_onKeyPress != null))
        {
            KeyboardHookStruct MyKeyboardHookStruct;
            if (wParam >= 0x100)
            {
                MyKeyboardHookStruct = (KeyboardHookStruct)Marshal.PtrToStructure(lParam, typeof(KeyboardHookStruct));
                wParamAlt = false;
            }
            else
            {
                MyKeyboardHookStruct = new KeyboardHookStruct();
                MyKeyboardHookStruct.vkCode = wParam;
                if (wParamAlt)
                {
                    wParamAlt = (wParam == 18);
                    wParam = 0x104;
                }
                else
                {
                    wParamAlt = (wParam == 18);
                    wParam = 0x100;
                }
            }

            if (m_onKeyDown != null && (wParam == 0x100 || wParam == 0x104))
            {
                Keys keyData = (Keys)MyKeyboardHookStruct.vkCode;
                if (wParam == 0x104)
                    keyData |= Keys.Alt;
                KeyEventArgs e = new KeyEventArgs(keyData);
                m_onKeyDown(this, e);
                handled = handled || e.Handled;
            }

            if (m_onKeyPress != null && wParam == 0x100)
            {
                bool isShift = ((GetKeyState(0x10) & 0x80) == 0x80 ? true : false);
                bool isCapslock = (GetKeyState(0x14) != 0 ? true : false);

                byte[] keyState = new byte[256];
                GetKeyboardState(keyState);
                byte[] inBuffer = new byte[2];
                if (ToAscii(MyKeyboardHookStruct.vkCode, MyKeyboardHookStruct.scanCode, keyState, inBuffer, MyKeyboardHookStruct.flags) == 1)
                {
                    char key = (char)inBuffer[0];
                    if ((isCapslock ^ isShift) && Char.IsLetter(key))
                        key = Char.ToUpper(key);
                    KeyPressEventArgs e = new KeyPressEventArgs(key);
                    m_onKeyPress(this, e);
                    handled = handled || e.Handled;
                }
            }

            if (m_onKeyUp != null && (wParam == 0x101 || wParam == 0x105))
            {
                Keys keyData = (Keys)MyKeyboardHookStruct.vkCode;
                if (wParam == 0x105)
                    keyData |= Keys.Alt;
                KeyEventArgs e = new KeyEventArgs(keyData);
                m_onKeyUp(this, e);
                handled = handled || e.Handled;
            }
        }

        if (handled)
            return (IntPtr)1;
        else
            return CallNextHookEx(m_Hook, nCode, (IntPtr)wParam, (IntPtr)lParam);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM