Answered by:
Capture click Anywhere

Question
-
Trying to capture a click anywhere on the screen and having problems when I use code snippet i found. getting the following error:
Managed Debugging Assistant 'PInvokeStackImbalance' has detected a problem in 'C:\Users\mholmes\Documents\Visual Studio 2015\Projects\Mouse Macro Tool\Mouse Macro Tool\bin\Debug\Mouse Macro Tool.vshost.exe'
snippet:
[DllImport("user32.dll")] static extern bool GetCursorPos(ref Point lpPoint); [DllImport("user32.dll", CallingConvention = CallingConvention.Cdecl)] public static extern int GetAsyncKeyState(long vKey);
private void tmrMouseMove_Tick(object sender, EventArgs e) { try { Point pt = new Point(); GetCursorPos(ref pt); lblMouseLocation.Text = pt.X.ToString() + " , " + pt.Y.ToString(); if(GetAsyncKeyState(1) == 1) { MessageBox.Show("Left click"); } if(GetAsyncKeyState(2) ==1) { MessageBox.Show("Right Click"); } } catch(Exception ex) { } }
What am I doing wrong here?
Tuesday, June 5, 2018 6:48 PM
Answers
-
GetAsyncKeyState declaration is wrong
[DllImport("User32.dll", SetLastError = true)] private static extern short GetAsyncKeyState(System.Windows.Forms.Keys vKey);
thenif ((GetAsyncKeyState(System.Windows.Forms.Keys.LButton) & unchecked((int)0x80000000)) != 0) { // code for left click }
etc...- Edited by Castorix31 Tuesday, June 5, 2018 7:28 PM
- Marked as answer by old_School Wednesday, June 6, 2018 5:49 PM
Tuesday, June 5, 2018 7:25 PM
All replies
-
Ok I found a working method but its using a seperate task method and throwing a error. I dont know enough about multi threading to fix this issue:
error:
An exception of type 'System.ApplicationException' occurred in mscorlib.dll but was not handled in user code
Additional information: Object synchronization method was called from an unsynchronized block of code.code:
private void StartWaitingForClickFromOutside() { try { if (checking.WaitOne(10)) { var ctx = new SynchronizationContext(); are.Reset(); Task.Factory.StartNew(() => { while (true) { if (are.WaitOne(1)) { break; } if (MouseButtons == MouseButtons.Left) { ctx.Send(CLickFromOutside, null); //you might need to put in a delay here and not break depending on what you want to accomplish break; } } checking.ReleaseMutex(); }); } } catch (Exception ex) { } }
Tuesday, June 5, 2018 7:13 PM -
GetAsyncKeyState declaration is wrong
[DllImport("User32.dll", SetLastError = true)] private static extern short GetAsyncKeyState(System.Windows.Forms.Keys vKey);
thenif ((GetAsyncKeyState(System.Windows.Forms.Keys.LButton) & unchecked((int)0x80000000)) != 0) { // code for left click }
etc...- Edited by Castorix31 Tuesday, June 5, 2018 7:28 PM
- Marked as answer by old_School Wednesday, June 6, 2018 5:49 PM
Tuesday, June 5, 2018 7:25 PM -
Thank you so much works.Wednesday, June 6, 2018 5:49 PM