Capturing Key Events in Add-In

M

Mike Oliver

I'm trying to capture key events that trigger commands (default or
custom) in a add-in for Word. I'm not writing a macro, so there is no
OnKey event that I can tap into.

I've tried to install a low-level keyboard hook, but when I do that,
Word (Office 2003) crashes as soon as the user hits any key. (See C#
code below). Am I doing something wrong?

I could inspect any WM_KEYDOWN messages sent to the HWND of the
document window, but there isn't really an easy way to access the
underlying HWND (and subclass it) for a document through the object
model, is there?

What I'm trying to do at a higher level is trap all ways that a user
can do such commands as Save, Print, Copy, Paste, etc... (I've trapped
the CommandBar .Click events fine, but the Ctrl+... keyboard
accelerators are what have me beat currently).

Any help would be appreciated.

Mike Oliver

**code snippet**

[DllImport("kernel32")]
public static extern int GetCurrentThreadId();

[DllImport( "user32",CharSet=CharSet.Auto,CallingConvention=CallingConvention.StdCall)]
public static extern int SetWindowsHookEx(HookType idHook,HOOKPROC
lpfn,int hmod,int dwThreadId);

public enum HookType
{
WH_KEYBOARD = 2
}

public delegate int HOOKPROC(int nCode, int wParam, int lParam);

public void SetHook()
{
// set the keyboard hook
SetWindowsHookEx(HookType.WH_KEYBOARD,new
HOOKPROC(KeyboardProc),0,GetCurrentThreadId());
}

public int KeyboardProc(int nCode, int wParam, int lParam)
{
//Perform your process
return 0;
}

public void OnStartupComplete(ref System.Array custom)
{
SetHook(); // setting hook will cause crash in Word as soon as user
hits a key
}
 
C

Chad DeMeyer

Mike,

One alternative is to simply replace the built-in commands with your own
code. This can be done by giving a subprocedure the same name as the
built-in command, e.g., "Sub FilePrint", "Sub FilePrintDefault", etc. You
can determine the names of built-in commands by going to Tools|Macro|Macros,
and selecting "Word Commands" in the "Macros in:" dropdown.

If you do this, and click on the Word Command in the list that you want to
replace, you can then select the document or template you are coding in in
the "Macros in:" dropdown and click Create. Word will create a macro in
that VBA project with the default code for the command, which you can
include in your custom code to ensure that no desired functionality is lost.

Regards,
Chad
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top