Office插件开发之在Ribbon中的Button添加快捷键方法
准备工作:根据上一篇Office插件开发之VS2008创建Office 2007插件项目的方法 我们接着在group中添加一个Button,属性设置如下图:
思路:
(巧妇难为无米之炊,下面的想法是基于MS给我们提供了相应的API)
step1:添加快捷键也就是捕捉键盘输入事件,因此我们需要定义一个delegate,
delegate int HookProcKeyboard(int code, IntPtr wParam, IntPtr lParam);
并将键盘信息处理内容传给这个委托:
this.KeyboardProcDelegate = new HookProcKeyboard(this.KeyboardProc);
step2:如何处理键盘按键信息:我们先定义一根链条(指针):private IntPtr khook;
将每次的组合按键信息挂到一条链上, khook = SetWindowsHookEx(WH_KEYBOARD, this.KeyboardProcDelegate, IntPtr.Zero, id);
再对这个链条上的信息进行判断: if ((int)wParam == (int)'3' && ((int)lParam & KF_ALTDOWN) != 0){...}
相关的API:
下面是代码:
1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Text;
5using Microsoft.Office.Tools.Ribbon;
6using System.Windows.Forms;
7using System.Runtime.InteropServices;
8
9namespace ExcelAddIn1
10{
11 public partial class Ribbon2 : OfficeRibbon
12 {
13 constants#region constants
14 private const int WH_KEYBOARD = 2;
15 private const int HC_ACTION = 0;
16 private const int KF_ALTDOWN = 1 << 29;
17 #endregion
18
19 delegate int HookProcKeyboard(int code, IntPtr wParam, IntPtr lParam);
20 private HookProcKeyboard KeyboardProcDelegate = null;
21 private IntPtr khook;
22
23 public Ribbon2()
24 {
25 InitializeComponent();
26 }
27
28 private void Ribbon2_Load(object sender, RibbonUIEventArgs e)
29 {
30 //Init hook when you want to enable hot key.
31 InitHook();
32 }
33
34 private void InitHook()
35 {
36 uint id = GetCurrentThreadId();
37 this.KeyboardProcDelegate = new HookProcKeyboard(this.KeyboardProc);
38 //Init the keyboard hook with the thread id
39 khook = SetWindowsHookEx(WH_KEYBOARD, this.KeyboardProcDelegate, IntPtr.Zero, id);
40 }
41
42 private int KeyboardProc(int code, IntPtr wParam, IntPtr lParam)
43 {
44 try
45 {
46 if (code != HC_ACTION)
47 {
48 return CallNextHookEx(khook, code, wParam, lParam);
49 }
50 //Alt + 3
51 if ((int)wParam == (int)'3' && ((int)lParam & KF_ALTDOWN) != 0)
52 {
53 button1_Click(this, null);
54 }
55 //To ensure the next hot key press should be captured by default.
56 IntPtr h = GetFocus();
57 }
58 catch
59 {
60 }
61 return CallNextHookEx(khook, code, wParam, lParam);
62 }
63
64 private void button1_Click(object sender, RibbonControlEventArgs e)
65 {
66 MessageBox.Show("Hot key pressing is captured");
67 }
68
69 (invokestuff)#region (invokestuff)
70 [DllImport("kernel32.dll")]
71 static extern uint GetCurrentThreadId();
72 [DllImport("user32.dll")]
73 static extern IntPtr SetWindowsHookEx(int code, HookProcKeyboard func, IntPtr hInstance, uint threadID);
74 [DllImport("user32.dll")]
75 static extern bool UnhookWindowsHookEx(IntPtr hhk);
76 [DllImport("user32.dll")]
77 static extern int CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);
78 [DllImport("user32.dll")]
79 static extern IntPtr GetFocus();
80 #endregion
81 }
82}