The topic is described very well here , and there is even a ready-made class, but alas, this hook only works when the form is active, how can you make the hook even if the form is minimized and is not currently used at all? I would even call it a super-global hook.

I've created such a hook:

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Runtime.InteropServices; namespace com { public partial class Form1 : Form { public Form1() { InitializeComponent(); } [DllImport("user32.dll")] static extern IntPtr SetWindowsHookEx(int idHook, LowLevelKeyboardProc callback, IntPtr hInstance, uint threadId); [DllImport("user32.dll")] static extern bool UnhookWindowsHookEx(IntPtr hInstance); [DllImport("user32.dll")] static extern IntPtr CallNextHookEx(IntPtr idHook, int nCode, int wParam, IntPtr lParam); [DllImport("kernel32.dll")] static extern IntPtr LoadLibrary(string lpFileName); private delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam); const int WH_KEYBOARD_LL = 13; // Номер глобального LowLevel-хука на клавиатуру const int WM_KEYDOWN = 0x100; // Сообщения нажатия клавиши private LowLevelKeyboardProc _proc = hookProc; private static IntPtr hhook = IntPtr.Zero; public void SetHook() { IntPtr hInstance = LoadLibrary("User32"); hhook = SetWindowsHookEx(WH_KEYBOARD_LL, _proc, hInstance, 0); } public static void UnHook() { UnhookWindowsHookEx(hhook); } public static IntPtr hookProc(int code, IntPtr wParam, IntPtr lParam) { if (code >= 0 && wParam == (IntPtr)WM_KEYDOWN) { int vkCode = Marshal.ReadInt32(lParam); //////ОБРАБОТКА НАЖАТИЯ myfunc(); // ошибка return (IntPtr)1; } else return CallNextHookEx(hhook, code, (int)wParam, lParam); } private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e) { // убираем хук UnHook(); } private void Form1_Load(object sender, EventArgs e) { SetHook(); } public void myfunc(){ MessageBox.Show("Hello!"); } } } 

But the problem is that I cannot start my function in this case, an error occurs:

Error 1 A non-static field, method, or property "com.Form1.myfunc ()" requires an object reference

  • Please do not poke the links, but the code (class) is laid out here, it will be easier for me to understand, and others may need it. - Smash
  • 3
    This topic is easily googled, I see no reason to copy-paste the code also here - Specter
  • somehow everything is confused, ready class would be. - Smash
  • Here everyone poke links to topics with hooks. And the person asked a question on c #. Solution: Try static static myfunk (). - Vladislav Buzmakov

2 answers 2

How to install Windows trap in Visual C #

Global Mouse and Keyboard Hooks in C #

Global System Hooks in .NET

Everything works, define an instance of the class.

 Form1 B = new Form1(); B.myfunc(); 

and it will work