Application in vstoProgramIn some cases, you need to hook up the keyboard to implement some special functions such as shortcut key operations. In this case, use the P/invoke function for implementation, refer to the following:
Initialize and uninstall hooks during vsto loading and uninstalling
Code
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 ();
}
}
// The specific processing logic of the hook is:
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 );
}
}