SoFunction
Updated on 2025-03-01

C# Winform implements the implementation code of win and alt+F4 for blocking keyboards


using System;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
namespace WindowsApplication10
{
public partial class Form1 : Form
{
// Install the hook
[DllImport("")]
public static extern int SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId);
// Unload hook
[DllImport("")]
public static extern bool UnhookWindowsHookEx(int idHook);
// Continue with the next hook
[DllImport("")]
public static extern int CallNextHookEx(int idHook, int nCode, Int32 wParam, IntPtr lParam);
//Declaration definition
public delegate int HookProc(int nCode, Int32 wParam, IntPtr lParam);
static int hKeyboardHook = 0;
HookProc KeyboardHookProcedure;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
HookStart();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
HookStop();
}
// Install the hook
public void HookStart()
{
if (hKeyboardHook == 0)
{
// Create a HookProc instance
KeyboardHookProcedure = new HookProc(KeyboardHookProc);
//Define global hook
hKeyboardHook = SetWindowsHookEx(13, KeyboardHookProcedure, (().GetModules()[0]), 0);
if (hKeyboardHook == 0)
{
HookStop();
throw new Exception("SetWindowsHookEx failed.");
}
}
}
//Hooks are what hooks need to do.
private int KeyboardHookProc(int nCode, Int32 wParam, IntPtr lParam)
{
// Here you can add code for other functions
return 1;
}
// Unload hook
public void HookStop()
{
bool retKeyboard = true;
if (hKeyboardHook != 0)
{
retKeyboard = UnhookWindowsHookEx(hKeyboardHook);
hKeyboardHook = 0;
}
if (!(retKeyboard)) throw new Exception("UnhookWindowsHookEx failed.");
}
}
}