答案是只有用鉤子
如圖所示
UserActivityHook
using System;
using System
using System
using System
using System
using System
namespace gma
{
/// <summary>
/// This class allows you to tap keyboard and mouse and / or to detect their activity even when an
/// application runes in background or does not have any user interface at all
/// common
/// </summary>
public class UserActivityHook
{
#region Windows structure definitions
/// <summary>
/// The POINT structure defines the x
/// </summary>
/// <remarks>
/// ?url=/library/en
/// </remarks>
[StructLayout(LayoutKind
private class POINT
{
/// <summary>
/// Specifies the x
/// </summary>
public int x;
/// <summary>
/// Specifies the y
/// </summary>
public int y;
}
/// <summary>
/// The MOUSEHOOKSTRUCT structure contains information about a mouse event passed to a WH_MOUSE hook procedure
/// </summary>
/// <remarks>
/// ?url=/library/en
/// </remarks>
[StructLayout(LayoutKind
private class MouseHookStruct
{
/// <summary>
/// Specifies a POINT structure that contains the x
/// </summary>
public POINT pt;
/// <summary>
/// Handle to the window that will receive the mouse message corresponding to the mouse event
/// </summary>
public int hwnd;
/// <summary>
/// Specifies the hit
/// </summary>
public int wHitTestCode;
/// <summary>
/// Specifies extra information associated with the message
/// </summary>
public int dwExtraInfo;
}
/// <summary>
/// The MSLLHOOKSTRUCT structure contains information about a low
/// </summary>
[StructLayout(LayoutKind
private class MouseLLHookStruct
{
/// <summary>
/// Specifies a POINT structure that contains the x
/// </summary>
public POINT pt;
/// <summary>
/// If the message is WM_MOUSEWHEEL
/// The low
/// away from the user; a negative value indicates that the wheel was rotated backward
/// One wheel click is defined as WHEEL_DELTA
///If the message is WM_XBUTTONDOWN
/// or WM_NCXBUTTONDBLCLK
/// and the low
///XBUTTON
///The first X button was pressed or released
///XBUTTON
///The second X button was pressed or released
/// </summary>
public int mouseData;
/// <summary>
/// Specifies the event
///LLMHF_INJECTED Test the event
///
///Specifies whether the event was injected
///
///Reserved
/// </summary>
public int flags;
/// <summary>
/// Specifies the time stamp for this message
/// </summary>
public int time;
/// <summary>
/// Specifies extra information associated with the message
/// </summary>
public int dwExtraInfo;
}
/// <summary>
/// The KBDLLHOOKSTRUCT structure contains information about a low
/// </summary>
/// <remarks>
/// ?url=/library/en
/// </remarks>
[StructLayout(LayoutKind
private class KeyboardHookStruct
{
/// <summary>
/// Specifies a virtual
/// </summary>
public int vkCode;
/// <summary>
/// Specifies a hardware scan code for the key
/// </summary>
public int scanCode;
/// <summary>
/// Specifies the extended
/// </summary>
public int flags;
/// <summary>
/// Specifies the time stamp for this message
/// </summary>
public int time;
/// <summary>
/// Specifies extra information associated with the message
/// </summary>
public int dwExtraInfo;
}
#endregion
#region Windows function imports
/// <summary>
/// The SetWindowsHookEx function installs an application
/// You would install a hook procedure to monitor the system for certain types of events
/// are associated either with a specific thread or with all threads in the same desktop as the calling thread
/// </summary>[Page]
/// <param name=\
/// [in] Specifies the type of hook procedure to be installed
/// </param>
/// <param name=\
/// [in] Pointer to the hook procedure
/// thread created by a different process
/// library (DLL)
/// </param>
/// <param name=\
/// [in] Handle to the DLL containing the hook procedure pointed to by the lpfn parameter
/// The hMod parameter must be set to NULL if the dwThreadId parameter specifies a thread created by
/// the current process and if the hook procedure is within the code associated with the current process
/// </param>
/// <param name=\
/// [in] Specifies the identifier of the thread with which the hook procedure is to be associated
/// If this parameter is zero
/// same desktop as the calling thread
/// </param>
/// <returns>
/// If the function succeeds
/// If the function fails
/// </returns>
/// <remarks>
/// ?url=/library/en
/// </remarks>
[DllImport(\
CallingConvention = CallingConvention
private static extern int SetWindowsHookEx(
int idHook
HookProc lpfn
IntPtr hMod
int dwThreadId);
/// <summary>
/// The UnhookWindowsHookEx function removes a hook procedure installed in a hook chain by the SetWindowsHookEx function
/// </summary>
/// <param name=\
/// [in] Handle to the hook to be removed
/// </param>
/// <returns>
/// If the function succeeds
/// If the function fails
/// </returns>
/// <remarks>
/// ?url=/library/en
/// </remarks>
[DllImport(\
CallingConvention = CallingConvention
private static extern int UnhookWindowsHookEx(int idHook);
/// <summary>
/// The CallNextHookEx function passes the hook information to the next hook procedure in the current hook chain
/// A hook procedure can call this function either before or after processing the hook information
/// </summary>
/// <param name=\
/// <param name=\
/// [in] Specifies the hook code passed to the current hook procedure
/// The next hook procedure uses this code to determine how to process the hook information
/// </param>
/// <param name=\
/// [in] Specifies the wParam value passed to the current hook procedure
/// The meaning of this parameter depends on the type of hook associated with the current hook chain
/// </param>
/// <param name=\
/// [in] Specifies the lParam value passed to the current hook procedure
/// The meaning of this parameter depends on the type of hook associated with the current hook chain
/// </param>
/// <returns>
/// This value is returned by the next hook procedure in the chain
/// The current hook procedure must also return this value
/// For more information
/// </returns>
/// <remarks>
/// ?url=/library/en
/// </remarks>[Page]
[DllImport(\
CallingConvention = CallingConvention
private static extern int CallNextHookEx(
int idHook
int nCode
int wParam
IntPtr lParam);
/// <summary>
/// The CallWndProc hook procedure is an application
/// function used with the SetWindowsHookEx function
/// to this callback function
/// or library
/// </summary>
/// <param name=\
/// [in] Specifies whether the hook procedure must process the message
/// If nCode is HC_ACTION
/// If nCode is less than zero
/// CallNextHookEx function without further processing and must return the
/// value returned by CallNextHookEx
/// </param>
/// <param name=\
/// [in] Specifies whether the message was sent by the current thread
/// If the message was sent by the current thread
/// </param>
/// <param name=\
/// [in] Pointer to a CWPSTRUCT structure that contains details about the message
/// </param>
/// <returns>
/// If nCode is less than zero
/// If nCode is greater than or equal to zero
/// and return the value it returns; otherwise
/// hooks will not receive hook notifications and may behave incorrectly as a result
/// procedure does not call CallNextHookEx
/// </returns>
/// <remarks>
/// ?url=/library/en
/// </remarks>
private delegate int HookProc(int nCode
/// <summary>
/// The ToAscii function translates the specified virtual
/// state to the corresponding character or characters
/// using the input language and physical keyboard layout identified by the keyboard layout handle
/// </summary>
/// <param name=\
/// [in] Specifies the virtual
/// </param>
/// <param name=\
/// [in] Specifies the hardware scan code of the key to be translated
/// The high
/// </param>
/// <param name=\
/// [in] Pointer to a
/// Each element (byte) in the array contains the state of one key
/// If the high
/// The low bit
/// only the toggle bit of the CAPS LOCK key is relevant
/// of the NUM LOCK and SCROLL LOCK keys is ignored
/// </param>
/// <param name=\
/// [out] Pointer to the buffer that receives the translated character or characters
/// </param>
/// <param name=\
/// [in] Specifies whether a menu is active
/// </param>
/// <returns>
/// If the specified key is a dead key
/// Value Meaning
///
///
///
/// (accent or diacritic) stored in the keyboard layout cannot be composed with the specified
/// virtual key to form a single character
/// </returns>
/// <remarks>
/// ?url=/library/en
/// </remarks>
[DllImport(\
private static extern int ToAscii(
int uVirtKey
int uScanCode
byte[] lpbKeyState
byte[] lpwTransKey
int fuState);
/// <summary>
/// The GetKeyboardState function copies the status of the
/// specified buffer
/// </summary>
/// <param name=\
/// [in] Pointer to a
/// </param>
/// <returns>
/// If the function succeeds
/// If the function fails
/// </returns>
/// <remarks>
/// ?url=/library/en
/// </remarks>
[DllImport(\
private static extern int GetKeyboardState(byte[] pbKeyState);
[DllImport(\
private static extern short GetKeyState(int vKey);
#endregion
#region Windows constants
//values from Winuser
/// <summary>
/// Windows NT/
/// </summary>
private const int WH_MOUSE_LL =
/// <summary>
/// Windows NT/
/// </summary>
private const int WH_KEYBOARD_LL =
/// <summary>
/// Installs a hook procedure that monitors mouse messages
/// </summary>
private const int WH_MOUSE =
/// <summary>
/// Installs a hook procedure that monitors keystroke messages
/// </summary>
private const int WH_KEYBOARD =
/// <summary>
/// The WM_MOUSEMOVE message is posted to a window when the cursor moves
/// </summary>
private const int WM_MOUSEMOVE =
/// <summary>
/// The WM_LBUTTONDOWN message is posted when the user presses the left mouse button
/// </summary>
private const int WM_LBUTTONDOWN =
/// <summary>
/// The WM_RBUTTONDOWN message is posted when the user presses the right mouse button
/// </summary>
private const int WM_RBUTTONDOWN =
/// <summary>
/// The WM_MBUTTONDOWN message is posted when the user presses the middle mouse button
/// </summary>
private const int WM_MBUTTONDOWN =
/// <summary>
/// The WM_LBUTTONUP message is posted when the user releases the left mouse button
/// </summary>
private const int WM_LBUTTONUP =
/// <summary>
/// The WM_RBUTTONUP message is posted when the user releases the right mouse button
/// </summary>
private const int WM_RBUTTONUP =
/// <summary>
/// The WM_MBUTTONUP message is posted when the user releases the middle mouse button
/// </summary>
private const int WM_MBUTTONUP =
/// <summary>
/// The WM_LBUTTONDBLCLK message is posted when the user double
/// </summary>
private const int WM_LBUTTONDBLCLK =
/// <summary>
/// The WM_RBUTTONDBLCLK message is posted when the user double
/// </summary>
private const int WM_RBUTTONDBLCLK =
/// <summary>
/// The WM_RBUTTONDOWN message is posted when the user presses the right mouse button
/// </summary>
private const int WM_MBUTTONDBLCLK =
/// <summary>
/// The WM_MOUSEWHEEL message is posted when the user presses the mouse wheel
/// </summary>
private const int WM_MOUSEWHEEL =
/// <summary>
/// The WM_KEYDOWN message is posted to the window with the keyboard focus when a nonsystem
/// key is pressed
/// </summary>[Page]
private const int WM_KEYDOWN =
/// <summary>
/// The WM_KEYUP message is posted to the window with the keyboard focus when a nonsystem
/// key is released
/// or a keyboard key that is pressed when a window has the keyboard focus
/// </summary>
private const int WM_KEYUP =
/// <summary>
/// The WM_SYSKEYDOWN message is posted to the window with the keyboard focus when the user
/// presses the F
/// presses another key
/// in this case
/// receives the message can distinguish between these two contexts by checking the context
/// code in the lParam parameter
/// </summary>
private const int WM_SYSKEYDOWN =
/// <summary>
/// The WM_SYSKEYUP message is posted to the window with the keyboard focus when the user
/// releases a key that was pressed while the ALT key was held down
/// window currently has the keyboard focus; in this case
/// to the active window
/// these two contexts by checking the context code in the lParam parameter
/// </summary>
private const int WM_SYSKEYUP =
private const byte VK_SHIFT =
private const byte VK_CAPITAL =
private const byte VK_NUMLOCK =
#endregion
/// <summary>
/// Creates an instance of UserActivityHook object and sets mouse and keyboard hooks
/// </summary>
/// <exception cref=\
public UserActivityHook()
{
Start();
}
/// <summary>
/// Creates an instance of UserActivityHook object and installs both or one of mouse and/or keyboard hooks and starts rasing events
/// </summary>
/// <param name=\
/// <param name=\
/// <exception cref=\
/// <remarks>
/// To create an instance without installing hooks call new UserActivityHook(false
/// </remarks>
public UserActivityHook(bool InstallMouseHook
{
Start(InstallMouseHook
}
/// <summary>
/// Destruction
/// </summary>
~UserActivityHook()
{
//uninstall hooks and do not throw exceptions
Stop(true
}
/// <summary>
/// Occurs when the user moves the mouse
/// </summary>
public event MouseEventHandler OnMouseActivity;
/// <summary>
/// Occurs when the user presses a key
/// </summary>
public event KeyEventHandler KeyDown;
/// <summary>
/// Occurs when the user presses and releases
/// </summary>
public event KeyPressEventHandler KeyPress;
/// <summary>
/// Occurs when the user releases a key
/// </summary>
public event KeyEventHandler KeyUp;
/// <summary>
/// Stores the handle to the mouse hook procedure
/// </summary>
private int hMouseHook =
/// <summary>
/// Stores the handle to the keyboard hook procedure
/// </summary>
private int hKeyboardHook =
/// <summary>
/// Declare MouseHookProcedure as HookProc type
/// </summary>
private static HookProc MouseHookProcedure;
/// <summary>
/// Declare KeyboardHookProcedure as HookProc type
/// </summary>
private static HookProc KeyboardHookProcedure;
/// <summary>
/// Installs both mouse and keyboard hooks and starts raising events
/// </summary>
/// <exception cref=\
public void Start()[Page]
{
this
}
/// <summary>
/// Installs both or one of mouse and/or keyboard hooks and starts raising events
/// </summary>
/// <param name=\
/// <param name=\
/// <exception cref=\
public void Start(bool InstallMouseHook
{
// install Mouse hook only if it is not installed and must be installed
if (hMouseHook ==
{
// Create an instance of HookProc
MouseHookProcedure = new HookProc(MouseHookProc);
//install hook
hMouseHook = SetWindowsHookEx(
WH_MOUSE_LL
MouseHookProcedure
Marshal
Assembly
//If SetWindowsHookEx fails
if (hMouseHook ==
{
//Returns the error code returned by the last unmanaged function called using platform invoke that has the DllImportAttribute
int errorCode = Marshal
//do cleanup
Stop(true
//Initializes and throws a new instance of the Win
throw new Win
}
}
// install Keyboard hook only if it is not installed and must be installed
if (hKeyboardHook ==
{
// Create an instance of HookProc
KeyboardHookProcedure = new HookProc(KeyboardHookProc);
//install hook
hKeyboardHook = SetWindowsHookEx(
WH_KEYBOARD_LL
KeyboardHookProcedure
Marshal
Assembly
//If SetWindowsHookEx fails
if (hKeyboardHook ==
{
//Returns the error code returned by the last unmanaged function called using platform invoke that has the DllImportAttribute
int errorCode = Marshal
//do cleanup
Stop(false
//Initializes and throws a new instance of the Win
throw new Win
}
}
}
/// <summary>
/// Stops monitoring both mouse and keyboard events and rasing events
/// </summary>
/// <exception cref=\
public void Stop()
{
this
}
/// <summary>
/// Stops monitoring both or one of mouse and/or keyboard events and rasing events
/// </summary>
/// <param name=\
/// <param name=\
/// <param name=\
/// <exception cref=\
public void Stop(bool UninstallMouseHook
{
//if mouse hook set and must be uninstalled
if (hMouseHook !=
{
//uninstall hook
int retMouse = UnhookWindowsHookEx(hMouseHook);
//reset invalid handle
hMouseHook =
//if failed and exception must be thrown
if (retMouse ==
{[Page]
//Returns the error code returned by the last unmanaged function called using platform invoke that has the DllImportAttribute
int errorCode = Marshal
//Initializes and throws a new instance of the Win
throw new Win
}
}
//if keyboard hook set and must be uninstalled
if (hKeyboardHook !=
{
//uninstall hook
int retKeyboard = UnhookWindowsHookEx(hKeyboardHook);
//reset invalid handle
hKeyboardHook =
//if failed and exception must be thrown
if (retKeyboard ==
{
//Returns the error code returned by the last unmanaged function called using platform invoke that has the DllImportAttribute
int errorCode = Marshal
//Initializes and throws a new instance of the Win
throw new Win
}
}
}
/// <summary>
/// A callback function which will be called every time a mouse activity detected
/// </summary>
/// <param name=\
/// [in] Specifies whether the hook procedure must process the message
/// If nCode is HC_ACTION
/// If nCode is less than zero
/// CallNextHookEx function without further processing and must return the
/// value returned by CallNextHookEx
/// </param>
/// <param name=\
/// [in] Specifies whether the message was sent by the current thread
/// If the message was sent by the current thread
/// </param>
/// <param name=\
/// [in] Pointer to a CWPSTRUCT structure that contains details about the message
/// </param>
/// <returns>
/// If nCode is less than zero
/// If nCode is greater than or equal to zero
/// and return the value it returns; otherwise
/// hooks will not receive hook notifications and may behave incorrectly as a result
/// procedure does not call CallNextHookEx
/// </returns>
private int MouseHookProc(int nCode
{
// if ok and someone listens to our events
if ((nCode >=
{
//Marshall the data from callback
MouseLLHookStruct mouseHookStruct = (MouseLLHookStruct)Marshal
//detect button clicked
MouseButtons button = MouseButtons
short mouseDelta =
switch (wParam)
{
case WM_LBUTTONDOWN:
//case WM_LBUTTONUP:
//case WM_LBUTTONDBLCLK:
button = MouseButtons
break;
case WM_RBUTTONDOWN:
//case WM_RBUTTONUP:
//case WM_RBUTTONDBLCLK:
button = MouseButtons
break;
case WM_MOUSEWHEEL:
//If the message is WM_MOUSEWHEEL
//One wheel click is defined as WHEEL_DELTA
//(value >>
mouseDelta = (short)((mouseHookStruct
//TODO: X BUTTONS (I havent them so was unable to test)
//If the message is WM_XBUTTONDOWN
//or WM_NCXBUTTONDBLCLK
//and the low
//Otherwise
break;
}
//double clicks
int clickCount =
if (button != MouseButtons
if (wParam == WM_LBUTTONDBLCLK || wParam == WM_RBUTTONDBLCLK) clickCount =
else clickCount =
//generate event
MouseEventArgs e = new MouseEventArgs(
button
clickCount
mouseHookStruct
mouseHookStruct
mouseDelta);
//raise it
OnMouseActivity(this
}
//call next hook
return CallNextHookEx(hMouseHook
}
/// <summary>
/// A callback function which will be called every time a keyboard activity detected
/// </summary>
/// <param name=\
/// [in] Specifies whether the hook procedure must process the message
/// If nCode is HC_ACTION
/// If nCode is less than zero
/// CallNextHookEx function without further processing and must return the
/// value returned by CallNextHookEx
/// </param>
/// <param name=\
/// [in] Specifies whether the message was sent by the current thread
/// If the message was sent by the current thread
/// </param>
/// <param name=\
/// [in] Pointer to a CWPSTRUCT structure that contains details about the message
/// </param>
/// <returns>
/// If nCode is less than zero
/// If nCode is greater than or equal to zero
/// and return the value it returns; otherwise
/// hooks will not receive hook notifications and may behave incorrectly as a result
/// procedure does not call CallNextHookEx
/// </returns>
private int KeyboardHookProc(int nCode
{
//indicates if any of underlaing events set e
bool handled = false;
//it was ok and someone listens to events
if ((nCode >=
{
//read structure KeyboardHookStruct at lParam
KeyboardHookStruct MyKeyboardHookStruct = (KeyboardHookStruct)Marshal
//raise KeyDown
if (KeyDown != null && (wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN))
{
Keys keyData = (Keys)MyKeyboardHookStruct
KeyEventArgs e = new KeyEventArgs(keyData);
KeyDown(this
handled = handled || e
}
// raise KeyPress
if (KeyPress != null && wParam == WM_KEYDOWN)
{
bool isDownShift = ((GetKeyState(VK_SHIFT) &
bool isDownCapslock = (GetKeyState(VK_CAPITAL) !=
byte[] keyState = new byte[
GetKeyboardState(keyState);
byte[] inBuffer = new byte[
if (ToAscii(MyKeyboardHookStruct
MyKeyboardHookStruct
keyState
inBuffer
MyKeyboardHookStruct
{
char key = (char)inBuffer[
if ((isDownCapslock ^ isDownShift) && Char
KeyPressEventArgs e = new KeyPressEventArgs(key);[Page]
KeyPress(this
handled = handled || e
}
}
// raise KeyUp
if (KeyUp != null && (wParam == WM_KEYUP || wParam == WM_SYSKEYUP))
{
Keys keyData = (Keys)MyKeyboardHookStruct
KeyEventArgs e = new KeyEventArgs(keyData);
KeyUp(this
handled = handled || e
}
}
//if event handled in application do not handoff to other listeners
if (handled)
return
else
return CallNextHookEx(hKeyboardHook
}
}
}
Form
using System;
using System
using System
using System
using System
using System
namespace WindowsApplication
{
/// <summary>
/// Form
/// </summary>
public class Form
{
private System
private System
private System
/// <summary>
/// 必需的設計器變量
/// </summary>
private System
public Form
{
//
// Windows 窗體設計器支持所必需的
//
InitializeComponent();
//
// TODO: 在 InitializeComponent 調用後添加任何構造函數代碼
//
}
/// <summary>
/// 清理所有正在使用的資源
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components
}
}
base
}
#region Windows 窗體設計器生成的代碼
/// <summary>
/// 設計器支持所需的方法
/// 此方法的內容
/// </summary>
private void InitializeComponent()
{
this
this
this
this
this
//
// textBox
//
this
this
this
this
this
//
// textBox
//
this
this
this
this
this
this
//
// panel
//
this
this
this
this
this
//
// Form
//
this
this
this
this
this
this
this
this
this
}
#endregion
/// <summary>
/// 應用程序的主入口點
/// </summary>
[STAThread]
static void Main()
{
Application
}
public void MyKeyDown(object sender
{
}
public void MyKeyPress(object sender
{
}
public void MyKeyUp(object sender
{
}
void choose_OnMouseActivity(object sender
{
//自定義右鍵
//if (ActiveControl
//if (ActiveControl
if (ActiveControl == textBox
{
MenuItem copy = new MenuItem(\
copy
MenuItem[] menuItems = new MenuItem[] { copy };
ContextMenu buttonMenu = new ContextMenu(menuItems);
textBox
//this
}
}
private void copy_Click(object sender
{
Clipboard
}
private void Form
{
//初始化
gma
choosesc
// choosesc
// choosesc
// choosesc
}
}
}
說明
From:http://tw.wingwit.com/Article/program/net/201311/13113.html