Invoke error why trying to run autoclicker - c#

I want to make an autoclicker that will click when i press "F" button; But each time I try to press "F" I get invoke error.
I tried to run Click thread in another void but it didn't work.
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern void mouse_event(long dwFlags, long dx, long dy, long cButtons, long dwExtraInfo);
UserActivityHook actHook;
static bool autoclickerToggle = false;
private const int MOUSEEVENTF_LEFTDOWN = 0x02;
private const int MOUSEEVENTF_LEFTUP = 0x04;
private const int MOUSEEVENTF_RIGHTDOWN = 0x08;
private const int MOUSEEVENTF_RIGHTUP = 0x10;
public Form1()
{
InitializeComponent();
actHook = new UserActivityHook(); // crate an instance with global hooks
// hang on events
actHook.OnMouseActivity += new MouseEventHandler(MouseMoved);
actHook.KeyDown += new KeyEventHandler(MyKeyDown);
actHook.KeyPress += new KeyPressEventHandler(MyKeyPress);
actHook.KeyUp += new KeyEventHandler(MyKeyUp);
}
public void MouseMoved(object sender, MouseEventArgs e) { }
public void MyKeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.F)
{
AutoclickerToggle();
}
}
public void MyKeyPress(object sender, KeyPressEventArgs e) { }
void AutoclickerToggle()
{
if (autoclickerToggle)
{
autoclickerToggle = false;
}
else
{
autoclickerToggle = true;
Thread Click = new Thread(() => Clicker());
Click.Start();
}
}
public void MyKeyUp(object sender, KeyEventArgs e) { }
public void Clicker()
{
while (autoclickerToggle)
{
int X = Cursor.Position.X;
int Y = Cursor.Position.Y;
mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, X, Y, 0, 0);
Thread.Sleep(100);
}
}
As I said I've got this error when pressing "F" (used translator there, because I had this error in polish language) "Calling PInvoke 'Test! Test.Form1 :: mouse_event 'has upset the balance of the stack. The likely cause is a mismatch between the managed PInvoke signature and the unmanaged target signature. Verify that the called convention and signature parameters of the PInvoke function match the unmanaged destination signature"

Related

System.ObjectDisposedException' with costum caret in WinForm C# application

In C# WinForm desktop application initialization I have custom caret event handler:
public Form1()
{
InitializeComponent();
textBox1.GotFocus += new EventHandler(textBox1_GotFocus);
}
then textBox1_KeyDown shows caret:
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
ShowCaret(textBox1.Handle);
}
And from textBox1_TextChanged:
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (textBox1.Text.Length > 0)
{
int x = 0;
DrawCaret(textBox1, x);
}
else if (textBox1.Text.Length < 1)
{
int x = 1;
DrawCaret(textBox1, x);
}
}
And:
[DllImport("user32.dll")]
static extern bool CreateCaret(IntPtr hWnd, IntPtr hBitmap, int nWidth, int nHeight);
[DllImport("user32.dll")]
static extern bool ShowCaret(IntPtr hWnd);
void textBox1_GotFocus(object sender, EventArgs e)
{
int x = 1;
DrawCaret(textBox1, x);
}
int size;
public void DrawCaret(Control ctrl, int x)
{
if (x == 0) { size = 2; }
else { size = 15; }
var nHeight = textBox1.Height;
var nWidth = size;
nHeight = Font.Height;
CreateCaret(ctrl.Handle, IntPtr.Zero, nWidth, nHeight);
}
I get:
System.ObjectDisposedException' occurred in ShowCaret(ctrl.Handle);
Which shows exception on code line:
CreateCaret(ctrl.Handle, IntPtr.Zero, nWidth, nHeight);
But attached to static extern bool ShowCaret(IntPtr hWnd); above.
Can't figure out what causes this exception
Any guide, advice or example would be helpful

C# how to toggle simulated mouse clicks with left mouse button

I would like to so when I hold my left mouse button down it simulates clicks but this is not working as it's not simulating clicks but if I remove the if statement in the timer1, it simulates clicks but I want it to only simulate when I'm holding left mouse.
Here is my code so far what I've done. if you could help that would be great
public partial class Form1 : Form
{
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint cButtons, uint dwExtraInfo);
//Mouse actions
private const int MOUSEEVENTF_LEFTDOWN = 0x02;
private const int MOUSEEVENTF_LEFTUP = 0x04;
private const int MOUSEEVENTF_RIGHTDOWN = 0x08;
private const int MOUSEEVENTF_RIGHTUP = 0x10;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
timer1.Start();
}
private void button2_Click(object sender, EventArgs e)
{
timer1.Stop();
}
private void timer1_Tick(object sender, EventArgs e)
{
if (MouseButtons == MouseButtons.Left){
DoMouseClick();
}
}
public void DoMouseClick()
{
//Call the imported function with the cursor's current position
uint X = (uint)Cursor.Position.X;
uint Y = (uint)Cursor.Position.Y;
mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, X, Y, 0, 0);
}
}

Mouse move automation in windows service

I have created a Windows Service,
In the On start method, i am invoking a Listener for an input device
public class LeapMouseServiceService : ServiceBase
{
private Controller cnt;
private LeapListener ls;
public LeapMouseServiceService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
this.cnt.AddListener(ls);
}
MouseOpera has mouse_event from USer32.dll
class MouseOpera
{
[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern bool SetCursorPos(int x, int y);
[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern void mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo);
private const int MOUSEEVENTF_MOVE = 0x01;
private const int MOUSEEVENTF_LEFTDOWN = 0x02;
private const int MOUSEEVENTF_LEFTUP = 0x04;
private const int MOUSEEVENTF_RIGHTDOWN = 0x08;
private const int MOUSEEVENTF_RIGHTUP = 0x10;
public static void DeltaMove(int x, int y)
{
mouse_event(MOUSEEVENTF_MOVE, x, y, 0, 0);
}
LeapListener Class has Onframe method
class LeapListener : Listener
{
private Object thisLock = new Object();
System.IO.StreamWriter sw = new System.IO.StreamWriter(#"K:\logs\log.txt",true);
private void SafeWriteLine(String line)
{
lock (thisLock)
{
sw.WriteLine(line);
}
}
public override void OnInit(Controller controller)
{
SafeWriteLine(DateTime.Now.ToShortDateString());
SafeWriteLine("Initialized");
}
public override void OnConnect(Controller controller)
{
SafeWriteLine("Connected");
}
public override void OnDisconnect(Controller controller)
{
//Note: not dispatched when running in a debugger.
SafeWriteLine("Disconnected");
}
public override void OnExit(Controller controller)
{
SafeWriteLine("Exited");
}
public override void OnFrame(Controller controller)
{
// Get the most recent frame and report some basic information
Frame frame = controller.Frame();
MouseOpera.DeltaMove((int)(hand.Direction.Yaw*10),-(int)(hand.Direction.Pitch*10));
The log.txt is perfectly capturing all Leap activities when Service is running. But, the mouse movement is not happening. How to make the mouse move automatically from windows service using C# code?

How to detect a keybd_event without focus

I'm working on a program, who need to detect when the user press the keyboard or use his mouse, even if the program is minimized or not focused.
I think I have to use the windows API, keybd_event (user32), but I don't know how to use the "listener" of this event. I have something like that:
[DllImport("user32.dll")]
static extern void keybd_event(byte bVk, byte bScan, uint dwFlags,UIntPtr dwExtraInfo);
void PressKey(byte keyCode)
{
//My code here
}
I did some research, but it's the first time I have to use DllImport, so I don't know how to continue ...
Thanks
(Ps:Sorry about my bad English, this is not my native language :) )
(PPs: I've read all of your answers, but it takes a while to read every link, so I'll work on it tonight, but I think I will find the answer. Anyway, thanks for the links everybody ;) )
Edit: So I just finished my code and it's work :) It looks something like:
[DllImport("user32.dll")]
public static extern Boolean GetLastInputInfo(ref tagLASTINPUTINFO plii);
public struct tagLASTINPUTINFO
{
public uint cbSize;
public Int32 dwTime;
}
private void timerTemps_Inactif_Tick(object sender, EventArgs e)
{
tagLASTINPUTINFO LastInput = new tagLASTINPUTINFO();
Int32 IdleTime;
LastInput.cbSize = (uint)Marshal.SizeOf(LastInput);
LastInput.dwTime = 0;
if (GetLastInputInfo(ref LastInput))
{
IdleTime = System.Environment.TickCount - LastInput.dwTime;
if (IdleTime > 10000)
{
//My code here
}
}
}
Thanks for the help guys ;)
You will need to hook into Windows OS with SetWindowsHookEx function. You should read the article Keyloggers: How they work and how to detect them posted by SecureList to get a understanding ofthe process.
I have always got a good performance by using RegisterHotKey/UnregisterHotKey functions. Sample code:
[DllImport("User32")]
public static extern bool RegisterHotKey(
IntPtr hWnd,
int id,
int fsModifiers,
int vk
);
[DllImport("User32")]
public static extern bool UnregisterHotKey(
IntPtr hWnd,
int id
);
public const int MOD_SHIFT = 0x4;
public const int MOD_CONTROL = 0x2;
public const int MOD_ALT = 0x1;
public const int WM_HOTKEY = 0x312;
protected override void WndProc(ref Message m)
{
if (m.Msg == WM_HOTKEY && m.WParam == (IntPtr)0)
{
IntPtr lParamCTRLA = (IntPtr)4259842;
IntPtr lParamB = (IntPtr)4325376;
if (m.LParam == lParamCTRLA)
{
MessageBox.Show("CTRL+A was pressed");
}
else if (m.LParam == lParamB)
{
MessageBox.Show("B was pressed");
}
}
base.WndProc(ref m);
}
private void Form1_Load(object sender, EventArgs e)
{
this.FormClosing += new FormClosingEventHandler(Form1_FormClosing);
RegisterHotKey(this.Handle, 0, MOD_CONTROL, (int)Keys.A);
RegisterHotKey(this.Handle, 0, 0, (int)Keys.B);
}
private void Form1_FormClosing(Object sender, FormClosingEventArgs e)
{
UnregisterHotKey(this.Handle, 0);
}
You can "register" as many keys (or combination of keys) as you want by emulating the shown structure. All the registered keys will get inside the condition if (m.Msg == WM_HOTKEY && m.WParam == (IntPtr)0); if they are pressed at all (independently upon the program currently being selected). The easiest way to know the specific key/combination being pressed is relying on m.LParam (I got the two values I am including after a quick test with the given keys). You can do a quick research to find out a list of LParam or further constant modifiers (wheel of the mouse, for example).
The final code:
[DllImport("user32.dll")]
public static extern Boolean GetLastInputInfo(ref tagLASTINPUTINFO plii);
public struct tagLASTINPUTINFO
{
public uint cbSize;
public Int32 dwTime;
}
private void timerTemps_Inactif_Tick(object sender, EventArgs e)
{
tagLASTINPUTINFO LastInput = new tagLASTINPUTINFO();
Int32 IdleTime;
LastInput.cbSize = (uint)Marshal.SizeOf(LastInput);
LastInput.dwTime = 0;
if (GetLastInputInfo(ref LastInput))
{
IdleTime = System.Environment.TickCount - LastInput.dwTime;
if (IdleTime > 10000)
{
//My code here
}
}
}

error in PInvoke signature while trying to write mouse click code

class DoubleClickHover : Form
{
Thread T1;
System.Timers.Timer timer = new System.Timers.Timer(4000); //3 seconds
public DoubleClickHover()
{
T1 = new Thread(new ThreadStart(DoubleClickEvent));
timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
}
#region Timer Mouse Double Click event
//Here, the timer for Timer click event will start when mouse hovers over an area
private void form_MouseHover(object sender, System.EventArgs e)
{
timer.Start();
}
private void form_MouseLeave(object sender, System.EventArgs e)
{
timer.Stop();
}
void timer_Elapsed(object sender, ElapsedEventArgs e)
{
timer.Stop();
DoubleClickEvent();
}
//This method allows the user to click a file/folder by hovering/keeping still the mouse for specified time
public void DoubleClickEvent()
{
// Set the cursor position
// System.Windows.Forms.Cursor.Position();
DoClickMouse(0x2); // Left mouse button down
DoClickMouse(0x4); // Left mouse button up
DoClickMouse(0x2); // Left mouse button down
DoClickMouse(0x4); // Left mouse button up
}
static void DoClickMouse(int mouseButton)
{
var input = new INPUT()
{
dwType = 0, // Mouse input
mi = new MOUSEINPUT() { dwFlags = mouseButton }
};
if (SendInput(1, input, Marshal.SizeOf(input)) == 0)
{
throw new Exception();
}
}
[StructLayout(LayoutKind.Sequential)]
struct MOUSEINPUT
{
int dx;
int dy;
int mouseData;
public int dwFlags;
int time;
IntPtr dwExtraInfo;
}
struct INPUT
{
public uint dwType;
public MOUSEINPUT mi;
}
[DllImport("user32.dll", SetLastError = true)]
static extern uint SendInput(uint cInputs, INPUT input, int size);
#endregion
}
error:
A call to PInvoke function 'DoubleClickHover::SendInput' has unbalanced the stack. This is likely because the managed PInvoke signature does not match the unmanaged target signature. Check that the calling convention and parameters of the PInvoke signature match the target unmanaged signature.
please help.
thank u
Yes, your definition of SendInput is wrong. The second parameter is a pointer to a structure, which you need to declare as being passed by reference:
[DllImport("user32.dll", SetLastError = true)]
static extern uint SendInput(uint nInputs, ref INPUT pInputs, int cbSize);
Alternatively you could declare pInputs as an array (since that's what it really is):
[DllImport("user32.dll", SetLastError = true)]
static extern uint SendInput(uint nInputs, INPUT[] pInputs, int cbSize);

Categories

Resources