Глобал хук мыши - C#
Формулировка задачи:
Добрый день! У меня имеется глобал хук клавиатуры, сейчас мне понадобилось добавить хук мыши, создавать новый хук не хочется, как можно изменить имеющийся для записи перехвата нажатия клавишы мыши?
public int q; private static int lpdwProcessId; private static InputLanguageCollection installedInputLanguages = InputLanguage.InstalledInputLanguages; private static CultureInfo currentInputLanguage; public static Form2 ap = new Form2(); private const int WH_KEYBOARD_LL = 13; private const int WH_MOUSE = 7; private const int WM_KEYDOWN = 0x0100; private const int WM_LBUTTONDOWN = 0x201; private const int WM_CHAR = 0x0102; private const byte VK_SHIFT = 0x10; private const byte VK_CAPITAL = 0x14; private static LowLevelKeyboardProc _proc = new LowLevelKeyboardProc(HookCallback); private static IntPtr _hookID = IntPtr.Zero; public static Byte[] IpKeyState = new byte[256]; public static Byte[] pwszBuff = new byte[2]; public static string y = ""; [StructLayout(LayoutKind.Sequential)] private struct KeyboardHookStruct { public uint VirtualKeyCode; public uint ScanCode; public uint Flags; public int Time; public IntPtr ExtraInfo; } private delegate IntPtr KeyBoardProc(int nCode, IntPtr wParam, IntPtr lParam); private delegate IntPtr LowLevelKeyboardProc( int nCode, IntPtr wParam, IntPtr lParam); private static IntPtr SetHook(LowLevelKeyboardProc proc) { using (Process curProcess = Process.GetCurrentProcess()) using (ProcessModule curModule = curProcess.MainModule) { return SetWindowsHookEx(WH_KEYBOARD_LL, proc, GetModuleHandle(curModule.ModuleName), 0); } } private static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam) { IntPtr Tek = GetForegroundWindow(); if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN) { bool isDownShift = (GetKeyState(VK_SHIFT) & 0x80) == 0x80; bool isDownCapslock = GetKeyState(VK_CAPITAL) != 0; Int32 vkCode = Marshal.ReadInt32(lParam); var khs = (KeyboardHookStruct)Marshal.PtrToStructure(lParam, typeof(KeyboardHookStruct)); GetKeyboardState(IpKeyState); int localeId = GetKeyboardLayoutIdAtTime(); if (ToUnicodeEx(khs.VirtualKeyCode, khs.ScanCode, IpKeyState, pwszBuff, 2, 0, localeId) == 1) { UnicodeEncoding encoding = new UnicodeEncoding(); y = encoding.GetString(pwszBuff); if (((isDownShift == true) && (isDownCapslock == false)) || ((isDownShift == false) && (isDownCapslock == true))) { y.ToUpper(); isDownShift = false; isDownCapslock = false; } IntPtr wnd = GetForegroundWindow(); GetWindowThreadProcessId(wnd, out lpdwProcessId); if (lpdwProcessId == Data.id) switch (khs.VirtualKeyCode) { case 13: using (StreamWriter F = new StreamWriter(Data.path, true)) { F.WriteLine(""); F.Close(); } break; case 8: using (StreamWriter F = new StreamWriter(Data.path, true)) { F.Write(" -BACKSPACE- "); F.Close(); } break; case 9: using (StreamWriter F = new StreamWriter(Data.path, true)) { F.WriteLine("TAB"); F.Close(); } break; case 46: using (StreamWriter F = new StreamWriter(Data.path, true)) { F.Write(" -DELETE- "); F.Close(); } break; case 160: break; case 161: break; default: using (StreamWriter F = new StreamWriter(Data.path, true)) { F.Write("" + y); F.Close(); } break; } } if ((Keys)vkCode == Keys.Home) { ap.Start(); } if ((Keys)vkCode == Keys.End) { ap.Stop(); } lParam = (IntPtr)0; } return CallNextHookEx(_hookID, nCode, wParam, lParam); } static string GetWindowText(IntPtr hWnd) { int len = GetWindowTextLength(hWnd) + 1; StringBuilder sb = new StringBuilder(len); len = GetWindowText(hWnd, sb, len); return sb.ToString(0, len); } public void Start() { _hookID = SetHook(_proc); public void Stop() { UnhookWindowsHookEx(_hookID); _hookID = IntPtr.Zero; } [DllImport("USER32.DLL")] public static extern int GetKeyState(byte keys); [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] private static extern int ToUnicodeEx(uint wVirtKey, uint vScanCode, Byte[] IpKeyState, byte[] pwszBuff, int cchBuff, uint wFlags, int gl); [DllImport("USER32.DLL")] private static extern int GetKeyboardState(Byte[] IpKeyState); [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] private static extern IntPtr SetWindowsHookEx(int idHook, LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId); [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool UnhookWindowsHookEx(IntPtr hhk); [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam); [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] private static extern IntPtr GetModuleHandle(string lpModuleName); [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] private static extern IntPtr GetForegroundWindow(); [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)] private static extern IntPtr GetKeyboardLayout(int WindowsThreadProcessID); [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)] private static extern int GetWindowThreadProcessId(IntPtr handleWindow, out int lpdwProcessID); [DllImport("user32.dll")] public static extern int MapVirtualKeyEx(int uCode, int uMapType, int dwhkl); [DllImport("user32.dll", SetLastError = true)] static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount); [DllImport("user32.dll", SetLastError = true)] static extern int GetWindowTextLength(IntPtr hWnd);
Решение задачи: «Глобал хук мыши»
textual
Листинг программы
class InterceptMouse { private static LowLevelMouseProc _proc = HookCallback; private static IntPtr _hookID = IntPtr.Zero; public static void Main() { _hookID = SetHook(_proc); Application.Run(); UnhookWindowsHookEx(_hookID); } private static IntPtr SetHook(LowLevelMouseProc proc) { using (Process curProcess = Process.GetCurrentProcess()) using (ProcessModule curModule = curProcess.MainModule) { return SetWindowsHookEx(WH_MOUSE_LL, proc, GetModuleHandle(curModule.ModuleName), 0); } } private delegate IntPtr LowLevelMouseProc(int nCode, IntPtr wParam, IntPtr lParam); private static IntPtr HookCallback( int nCode, IntPtr wParam, IntPtr lParam) { if (nCode >= 0 && MouseMessages.WM_LBUTTONDOWN == (MouseMessages)wParam) { MSLLHOOKSTRUCT hookStruct = (MSLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(MSLLHOOKSTRUCT)); Console.WriteLine(hookStruct.pt.x + ", " + hookStruct.pt.y); } return CallNextHookEx(_hookID, nCode, wParam, lParam); } private const int WH_MOUSE_LL = 14; private enum MouseMessages { WM_LBUTTONDOWN = 0x0201, WM_LBUTTONUP = 0x0202, WM_MOUSEMOVE = 0x0200, WM_MOUSEWHEEL = 0x020A, WM_RBUTTONDOWN = 0x0204, WM_RBUTTONUP = 0x0205 } [StructLayout(LayoutKind.Sequential)] private struct POINT { public int x; public int y; } [StructLayout(LayoutKind.Sequential)] private struct MSLLHOOKSTRUCT { public POINT pt; public uint mouseData; public uint flags; public uint time; public IntPtr dwExtraInfo; } [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] private static extern IntPtr SetWindowsHookEx(int idHook, LowLevelMouseProc lpfn, IntPtr hMod, uint dwThreadId); [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool UnhookWindowsHookEx(IntPtr hhk); [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam); [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] private static extern IntPtr GetModuleHandle(string lpModuleName); }
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д