I want to make a C# Application with a Keyboard and Mouse on screen.
Every Key or Button that is clicked should be seen in this Application by for example coloring one of the keys ( i know how to do that ). This should also work if the Application is not focused. Currently i am using a global Key- and Mousehook which works fine.
The problem is, the Keyhook does only intercept one Key at a time which means i can only show on Key at a time. I want to be able to show multiple keys at a time on screen.
KeyListeners are unfortunately no option because they dont work outside the Application.
Does anyone has an idea how to make this possible?
Here's the KeyHook i am using:
public class KeyHook
{
private delegate int HookProc(int nCode, IntPtr wParam, IntPtr lParam);
static int hHook = 0;
public static List<Keys> KeyCodes = new List<Keys>();
const int WH_KEYBOARD_LL = 13;
HookProc KeyboardHookProcedure;
[StructLayout(LayoutKind.Sequential)]
private class keyboardHookStruct
{
public int vkCode;
public int scanCode;
public int flags;
public int time;
public int dwExtraInfo;
}
[DllImport("user32.dll", CharSet = CharSet.Auto,
CallingConvention = CallingConvention.StdCall)]
private static extern int SetWindowsHookEx(int idHook, HookProc lpfn,
IntPtr hInstance, int threadId);
[DllImport("user32.dll", CharSet = CharSet.Auto,
CallingConvention = CallingConvention.StdCall)]
private static extern bool UnhookWindowsHookEx(int idHook);
[DllImport("user32.dll", CharSet = CharSet.Auto,
CallingConvention = CallingConvention.StdCall)]
private static extern int CallNextHookEx(int idHook, int nCode,
IntPtr wParam, IntPtr lParam);
[DllImport("kernel32.dll")]
static extern IntPtr LoadLibrary(string lpFileName);
public KeyHook()
{
Hook();
}
~KeyHook()
{
UnHook();
}
public int Hook()
{
KeyboardHookProcedure = new HookProc(KeyHook.KeyboardHookProc);
hHook = SetWindowsHookEx(WH_KEYBOARD_LL, KeyboardHookProcedure, (IntPtr)LoadLibrary("User32"), 0);
return hHook;
}
public bool UnHook()
{
bool ret = UnhookWindowsHookEx(hHook);
if (ret)
hHook = 0;
return ret;
}
private static int KeyboardHookProc(int nCode, IntPtr wParam, IntPtr lParam)
{
if (nCode < 0)
{
return CallNextHookEx(hHook, nCode, wParam, lParam);
}
else
{
if (((int)wParam == 256) || ((int)wParam == 260))
{
keyboardHookStruct MyKeyboardHookStruct = (keyboardHookStruct)Marshal.PtrToStructure(lParam, typeof(keyboardHookStruct));
//Adding Key to a log i use for other stuff
KeyCodes.Add((Keys)MyKeyboardHookStruct.vkCode);
//Code for coloring Key in the UI for pressed Key
}
return CallNextHookEx(hHook, nCode, wParam, lParam);
}
}
}
Related
I'm trying to disable specific keys when a specific process is detected, but for a reason, it's not set the hook correctly so it's not working.
The code should do:
Detect if notepad.exe has been detected (already coded the function but i didnt write it here).
Now from the checking thread, it will start the hook thread which will implement a low-level keyboard hook to prevent the user from using specific keys into the target process.
here is the code that I'm using:
[StructLayout(LayoutKind.Sequential)]
private struct KBDLLHOOKSTRUCT
{
public Keys key;
public int scanCode;
public int flags;
public int time;
public IntPtr extra;
}
//System level functions to be used for hook and unhook keyboard input
private delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr SetWindowsHookEx(int id, LowLevelKeyboardProc callback, IntPtr hMod, uint dwThreadId);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern bool UnhookWindowsHookEx(IntPtr hook);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr CallNextHookEx(IntPtr hook, int nCode, IntPtr wp, IntPtr lp);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr GetModuleHandle(string name);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern short GetAsyncKeyState(Keys key);
//Declaring Global objects
private static IntPtr ptrHook;
private static LowLevelKeyboardProc objKeyboardProcess;
private const int WH_KEYBOARD_LL = 13;
private const int VK_CONTROL = 0x11;
public void Control()
{
MessageBox.Show("Control thread has been started");
ProcessModule objCurrentModule = Process.GetProcessesByName("notepad")[0].MainModule;
objKeyboardProcess = new LowLevelKeyboardProc(captureKey);
SetWindowsHookEx(13, objKeyboardProcess, GetModuleHandle(objCurrentModule.ModuleName), 0);
}
public static IntPtr captureKey(int nCode, IntPtr wp, IntPtr lp)
{
if (nCode >= 0)
{
KBDLLHOOKSTRUCT objKeyInfo = (KBDLLHOOKSTRUCT)Marshal.PtrToStructure(lp, typeof(KBDLLHOOKSTRUCT));
MessageBox.Show("ncode >=0 !");
if (objKeyInfo.key == Keys.G || objKeyInfo.key == Keys.H || objKeyInfo.key == Keys.S) // Disabling Windows keys
{
MessageBox.Show("One of the specific keys has been detected!");
return (IntPtr)1;
}
}
return CallNextHookEx(ptrHook, nCode, wp, lp);
}
public static void Dispose()
{
UnhookWindowsHookEx(ptrHook);
}
public static void Hide()
{
ProcessModule objCurrentModule = Process.GetCurrentProcess().MainModule;
objKeyboardProcess = new LowLevelKeyboardProc(captureKey);
ptrHook = SetWindowsHookEx(13, objKeyboardProcess, GetModuleHandle(objCurrentModule.ModuleName), 0);
}
public Form1()
{
InitializeComponent();
Thread cont = new Thread(Control);
cont.start();
}
In Visual Studio C #, I'm creating an application that records mouse movements through hooking to track mouse movement.
This application works well under normal circumstances, but when the task manager or a particular game is running, the thread stops and the application does not work.
However, when I click the application window again, it tracks mouse movement again.
How do I get this application to work when I'm running Task Manager or a particular game?
class Hook
{
static private DateTime Set_time;
public static class GlobalMouseHook
{
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern int SetWindowsHookEx(int idHook, HookProc Ipfn, IntPtr hlnstance, int threadld);
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern bool UnhookWindowsHookEx(int idHook);
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern int CallNextHookEx(int idHook, int nCode, IntPtr wParam, IntPtr lParam);
public delegate int HookProc(int nCode, IntPtr wParam, IntPtr lParm);
}
public static class MouseHook
{
[StructLayout(LayoutKind.Sequential)]
public class POINT
{
public int x;
public int y;
}
[StructLayout(LayoutKind.Sequential)]
public class MouseHookStruct
{
public POINT pt;
public int hwnd;
public int wHitTestCode;
public int dwExtraInfo;
}
public const int WH_MOUSE_LL = 14;
public static int hookHandle = 0;
private static GlobalMouseHook.HookProc callbackDelegate;
public static void StartHook(DateTime Set_time)
{
Hook.Set_time = Set_time;
callbackDelegate = new GlobalMouseHook.HookProc(CallBack);
if (hookHandle != 0)
{
return;
}
hookHandle = GlobalMouseHook.SetWindowsHookEx(WH_MOUSE_LL, callbackDelegate, IntPtr.Zero, 0);
}
public static void StopHook()
{
GlobalMouseHook.UnhookWindowsHookEx(hookHandle);
}
private enum MouseMessages
{
WM_LBUTTONDOWN = 0x0201,
WM_LBUTTONUP = 0x0202,
WM_MOUSEMOVE = 0x0200,
WM_MOUSEWHEEL = 0x020A,
WM_RBUTTONDOWN = 0x0204,
WM_RBUTTONUP = 0x0205
}
public static int CallBack(int nCode, IntPtr wParam, IntPtr lParam)
{
MouseHookStruct mouseInput = (MouseHookStruct)Marshal.PtrToStructure(lParam, typeof(MouseHookStruct));
System.Diagnostics.Debug.WriteLine(mouseInput.pt.x + " : " + mouseInput.pt.y);
System.Diagnostics.Debug.WriteLine((MouseMessages)wParam);
System.Diagnostics.Debug.WriteLine(DateTime.Now-Set_time);
return GlobalMouseHook.CallNextHookEx(hookHandle, nCode, wParam, lParam);
}
}
}
I have attached additional code to use that hooking code.
public Form1 ()
{
Hook.MouseHook.StartHook (DateTime.Now);
InitializeComponent ();
}
I borrowed the following code I found online (the comments aren't even mine). When I click a button on my form, it waits and detects my next mouse click. Whatever I click on, it gets that information in the winHandle object inside the HookCallback method:
private static LowLevelMouseProc _proc = HookCallback;
private static IntPtr _hookID = IntPtr.Zero;
static IntPtr hHook = IntPtr.Zero;
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)
{
// The application runs to here when you click on the window whose handle you want to get
POINT cusorPoint;
bool ret = GetCursorPos(out cusorPoint);
// cusorPoint contains your cusor’s position when you click on the window
// Then use cusorPoint to get the handle of the window you clicked
IntPtr winHandle = WindowFromPoint(cusorPoint);
// winHandle is the Hanle you need
// Now you have get the handle, do what you want here
// ………………………………………………….
Debug.WriteLine("Handle: " + winHandle.ToString());
// Because the hook may occupy much memory, so remember to uninstall the hook after
// you finish your work, and that is what the following code does.
UnhookWindowsHookEx(hHook);
hHook = IntPtr.Zero;
// Here I do not use the GetActiveWindow(). Let's call the window you clicked "DesWindow" and explain my reason.
// I think the hook intercepts the mouse click message before the mouse click message delivered to the DesWindow's
// message queue. The application came to this function before the DesWindow became the active window, so the handle
// abtained from calling GetActiveWindow() here is not the DesWindow's handle, I did some tests, and What I got is always
// the Form's handle, but not the DesWindow's handle. You can do some test too.
//IntPtr handle = GetActiveWindow();
}
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);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool GetCursorPos(out POINT lpPoint);
[DllImport("user32.dll")]
static extern IntPtr WindowFromPoint(POINT Point);
private void GetProcess_Click(object sender, EventArgs e)
{
if (IntPtr.Zero == hHook){
using (Process curProcess = Process.GetCurrentProcess())
using (ProcessModule curModule = curProcess.MainModule)
{
hHook = SetWindowsHookEx(WH_MOUSE_LL, _proc,
GetModuleHandle(curModule.ModuleName), 0);
}
}
}
The problem is I need to use the information from that object elsewhere in my code. But, since it doesn't return that information, I'm not sure how I could get access to it.
I don't think I can return it because it goes instead over to the CallNextHookEx method; I've tried putting it in its own class, but inside the HookCallBack method I don't have access to this. or datasets or anything else.
So what can I do to get that information from outside the static method HookCallback?
I want to get acquainted with WinAPI in C#.
I need to write a global mouse hook in the console application. I found the code that does this job. But I have a console application, and I shouldn't use Application.Run () from Windows.Forms.
I need to forward messages about the coordinates of the mouse from winAPI directly to the console window without winForms. How can i do this?
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_MOUSEMOVE == (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);
}
Add system.windows.forms as a reference to your project.
using System.Windows.Forms;
It should be work then.
This is the code for my keyhooking class, but it doesn't work. I was wondering if someone can tell me why? I'm instansiating it in another Console application. The debug message gives the proper output, but the keyboard hook simply doesn't catch keys. I was hoping if someone could tell me why.
namespace GlobalHooks
{
public class InterceptKeys
{
private const int WH_KEYBOARD_LL = 13;
private const int WM_KEYDOWN = 0x0100;
private static IntPtr _hookID = IntPtr.Zero;
private static String keysHooked = String.Empty;
private static LowLevelHookProc keyboardHook;
public delegate IntPtr LowLevelHookProc(int nCode, Int32 wParam, IntPtr lParam);
public delegate void KeyboardHandleFunction(int vkCode);
public static event KeyboardHandleFunction keyHookReturn;
public InterceptKeys(KeyboardHandleFunction func)
{
keyHookReturn = func;
keyboardHook = new LowLevelHookProc(HookCallback);
}
public static void debug()
{
Console.Write("\n[Success!] _hookID: "+_hookID);
Console.Write("\n[Success!] keyboardProc: "+keyboardHook.ToString());
}
private IntPtr SetupHook(LowLevelHookProc keyProcess)
{
using (Process curProcess = Process.GetCurrentProcess())
using (ProcessModule curModule = curProcess.MainModule)
{
return SetWindowsHookEx(WH_KEYBOARD_LL, keyProcess,
GetModuleHandle(curModule.ModuleName), 0);
}
}
public void Hook()
{
_hookID = SetupHook(keyboardHook);
debug();
}
public void Unhook()
{
UnhookWindowsHookEx(_hookID);
}
public static void OnCallbackReturn(int nCode)
{
if (keyHookReturn != null)
{
keyHookReturn(nCode);
}
else
{
throw new Exception();
}
}
public static IntPtr HookCallback(int nCode, Int32 wParam, IntPtr lParam)
{
Console.WriteLine("Calledback"Wink;
if (nCode >= 0 && wParam == WM_KEYDOWN)
{
int vkCode = Marshal.ReadInt32(lParam);
Console.WriteLine((Keys)vkCode);
OnCallbackReturn(nCode);
}
return CallNextHookEx((int)_hookID, nCode, wParam, lParam);
}
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr SetWindowsHookEx(int idHook, LowLevelHookProc lpfn, IntPtr hMod, uint dwThreadId);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern bool UnhookWindowsHookEx(IntPtr hhk);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr CallNextHookEx(int hhk, int nCode, int wParam, IntPtr lParam);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr GetModuleHandle(string lpModuleName);
}
}
Are you calling Application.Run in your Main function?
The standard Console thread doesn't have a message loop, which is required for hooks to work properly, Application.Run takes care of that.