How to programatically trigger a mouse left click in C#? - c#

How could I programmatically trigger a left-click event on the mouse?
Thanks.
edit: the event is not triggered directly on a button. I'm aiming for the Windows platform.

To perform a mouse click:
[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);
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 DoMouseClick()
{
mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
}
To move the cursor where you want:
[DllImport("user32.dll")]
static extern bool SetCursorPos(int X, int Y);
public static void MoveCursorToPoint(int x, int y)
{
SetCursorPos(x, y);
}

If it's right on a button, you can use
button1.PerformClick();
Otherwise, you can check out this MSDN article which discusses simulating mouse (and keyboard) input.
Additionally, this project may be able to help you out as well. Under the covers, it uses SendInput.

https://web.archive.org/web/20140214230712/http://www.pinvoke.net/default.aspx/user32.sendinput
Use the Win32 API to send input.
Update:
Since I no longer work with Win32 API, I will not update this answer to be correct when the platform changes or websites become unavailable. Since this answer doesn't even conform to Stackoverflow standards (does not contain the answer itself, but rather a link to an external, now defunct resource), there's no point giving it any points or spending any more time on it.
Instead, take a look at this question on Stackoverflow, which I think is a duplicate:
How to simulate Mouse Click in C#?

Related

Transparent window application to overlay in Windows

I want to write an application to process certain user actions.
The application will be always transparent and should be click through. So, the window behind will be seen and as the transparent application is click through I should be able to click on the window behind. Only certain user actions(like double click) I want to handle in my transparent application.
Is it possible to achieve this? Any guidelines are appreciated.
You can make fake window click from your app:
[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);
private const int MOUSEEVENTF_LEFTDOWN = 0x02;
private const int MOUSEEVENTF_LEFTUP = 0x04;
private const int MOUSEEVENTF_RIGHTDOWN = 0x08;
private const int MOUSEEVENTF_RIGHTUP = 0x10;
private void Form_MouseClick(object sender, MouseEventArgs e)
{
this.Hide();
Point p = this.PointToScreen(e.Location);
mouse_event(MOUSEEVENTF_LEFTDOWN , p.X, p.Y, 0, 0);
mouse_event(MOUSEEVENTF_LEFTUP, p.X, p.Y, 0, 0);
this.Show();//since this.opacity = 0; form will never be really visible
}
Now on double click you can set what ever you want.
You can make a window that is transparent and click through. However, it's all or nothing. You can't be click through apart from double clicks.
So, to do what you want I believe you will need to use a global mouse hook to handle the double clicks. But that's going to require native code.
In fact, come to think of it, why do you need the transparent click through window at all?

C# Clicking on a certain point on the screen

I am trying to perform a mouse click through c#. I used the mouse_event function to do it.
private const int MOUSEEVENTF_LEFTDOWN = 0x02;
private const int MOUSEEVENTF_LEFTUP = 0x04;
[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);
I tried two methods :
Moving the mouse to the point and clicking it :
Cursor.Position = new Point(100, 100);
mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, Cursor.Position.X, Cursor.Position.Y, 0, 0);
Passing the x, y of the desired click to the function :
mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP,100, 100, 0, 0);
Either way, I'm this weird error :
Managed Debugging Assistant 'PInvokeStackImbalance' has detected a problem in 'C:\Users\or\Documents\Visual Studio 2010\Projects\ProjectName\ProjectName\bin\Debug\ProjectName.vshost.exe'.
Additional Information: A call to PInvoke function 'ProjectName!ProjectName.MainForm::mouse_event' 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.
Any ideas on a solution?
I would suggest you use the following p/invoke signature
private const uint MOUSEEVENTF_LEFTDOWN = 0x02;
private const uint MOUSEEVENTF_LEFTUP = 0x04;
[DllImport("user32.dll")]
public static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint cButtons, IntPtr dwExtraInfo);
Note, that while mouse_event is convenient, it has been superseded by SendInput. You can find a reasonable p/invoke declaration for SendInput and the Input structure at the following URL.
http://www.pinvoke.net/default.aspx/user32.SendInput
You have obviously got this code from legacy VB6 code. long is 64-bit in .NET and C#, unlike VB6 where it is 32-bit.
Switch from long to int, and it should be okay.
edit: I was a little fast: dwExtraInfo should be of type IntPtr.

Send keyboard and mouse events to DirectX application in C#?

I need to send global keystrokes and mouse events to another application, which is coincidentally using using DirectX. (No controls/handles other than the window itself)
For example, I need to hold key X for 2 seconds and then release it...
I need to push Right Click down on coordinates x:600 and y:350, move the mouse 100 pixels down and then release the Right Click.
I also need to push 2 or more keys at once, like X and Y, and stop X after 2 seconds and Y after 2 more seconds.
So basically I would need full control of the input system...
It would also be ideal if I could control the application while maximized or in background. (optionally)
For the skeptics... The teacher made a DirectX application for drawing for our school. I am asked to make an application that draws samples on it, like a train or flower or something... I will be reading images and use the input to set the color and click on the canvas...
There are some possibilities. You may have a look at System.Windows.Forms.SendKeys and you can pInvoke some Win32 functions like SetForegroundWindow(), LockSetForegroundWindow() from gdi32.dll or from user32.dll SetCursorPos() and mouse_event to perform clicks:
Here a snippet for the Mouse events I used a while ago.
/**
* Mouse functions
*/
[DllImport("user32.dll", ExactSpelling=true)]
public static extern long mouse_event(Int32 dwFlags, Int32 dx, Int32 dy, Int32 cButtons, Int32 dwExtraInfo);
[DllImport("user32.dll", ExactSpelling=true)]
public static extern void SetCursorPos(Int32 x, Int32 y);
public const Int32 MOUSEEVENTF_ABSOLUTE = 0x8000;
public const Int32 MOUSEEVENTF_LEFTDOWN = 0x0002;
public const Int32 MOUSEEVENTF_LEFTUP = 0x0004;
public const Int32 MOUSEEVENTF_MIDDLEDOWN = 0x0020;
public const Int32 MOUSEEVENTF_MIDDLEUP = 0x0040;
public const Int32 MOUSEEVENTF_MOVE = 0x0001;
public const Int32 MOUSEEVENTF_RIGHTDOWN = 0x0008;
public const Int32 MOUSEEVENTF_RIGHTUP = 0x0010;
public static void PerformLeftKlick(Int32 x, Int32 y)
{
SetCursorPos(x, y);
mouse_event(MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0);
mouse_event(MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
}
Hope that pushes you in the right direction. A good resource is http://pinvoke.net/
If you want to use a library for C# that will make your work easier then read following link -
http://www.codeproject.com/Articles/117657/InputManager-library-Track-user-input-and-simulate
Other than .Net C# you can use other language alternative like in Java where, there is no confusion of direct x or normal input -
http://docs.oracle.com/javase/7/docs/api/java/awt/Robot.html

Parsing HTML page shown in any web browser in C# or java?

I have a kind of funny and weird requirement this time. I have my account on Facebook and as you all know it is very popular for playing games. One of the applications that i came across was Click game in which a person has to click as many times as he can in span of 10 seconds. Well, one friend said he created some .Net code in C# that would automate the process of clicking on the button. Is it really possible or is he bluffing? If so, can anybody tell me how? I personally haven't seen him doing it. But he mentions this thing in front of my other friends. Any guidelines would be helpful. With much effort i clicked 92 times in 10 seconds and he said using some C# code he just kept a loop and clicked for 1500 times. Now i feel kind of inferior in front of him :p. Just 92 as against his 1500.
Thanks in advance :)
Even this code doesn't work. I can't see even a single click on my page made to facebook :-
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint dwData,int dwExtraInfo);
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 void DoMouseClick()
{
int X = Cursor.Position.X;
int Y = Cursor.Position.Y;
for (int x = 0; x < 1000; x++)
{
for (int y = 0; y < 600; y++)
{
mouse_event((uint)MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTDOWN, (uint)x, (uint)y, 0, 0);
}
}
}
Probably it doesn't work because mouse click is sent to OS not facebook.
In .net, you can interact with the page scripts in a WebBrowser control with the InvokeScript API and interact with the page DOM via the Document property.
I've seen what you're talking about, and I, too, know people who have ridiculous numbers in that game. Most likely what they are doing is manipulating the JavaScript call that gets passed back to the server and relaying a fake number.
It is possible, however, to simulate a mouse click in .Net. Here's the code to trigger it:
[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);
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 void DoMouseClick()
{
int X = Cursor.Position.X;
int Y = Cursor.Position.Y;
mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, X, Y, 0, 0);
}
As you can see, we're getting the X and Y positions from the mouse's current location; however, you can simulate a click anywhere on the screen so long as you know the coordinates.
If you run this code in a loop, and you get the X and Y coordinates of the button you're trying to press (possibly by delaying the click routine for a few seconds after execution so you have time to move your mouse to where the button is), you can accomplish what you're trying to do.
Note that I don't think this is how people are getting such large numbers in the game. Most likely you can edit the JavaScript calls via FireBug or similar developer tool and then send back fake data to the server.
A Test Framework like Selenium could used for such a challenge

Progress Bar in Setup Application

I have created a custom action for my setup project and have successfully implemented a form that displays a progress bar for a download step in my install (I'm using a WebClient in my custom action code). So I have two questions that relate to each other.
Is there any way to show a download progress bar in the main setup window rather than creating a separate form that I display as I have done? I would prefer this.
If not, then what can I do to cause my form to display in front of the actual setup window when I call form.ShowDialog()? I've also called BringToFront() on it which doesn't work either. It's there, but it's always behind the main setup window. Seems there has to be some way to get the correct z-order.
Thanks for your help.
So I gave up on the idea of integrating the progress bar into the actual installer screen, but it's just plain ridiculous what it takes to get the Windows Form to display on top. I have to get a handle to the installer Window and send it to the background because bringing the progress bar window forward simply won't work. I've moved to Mac development now so coming back to this is just frustrating. I remember thinking C# .NET was pretty cool. It's got NOTHING on Cocoa/Objective-C.
It's infuriating having a method called BringToFront() that simply ignores you. Why do I have to drop down to Windows API code to do something as fundamental to a GUI as managing the the Z-Order? Z-Order? Seriously?
In case you're wondering, here's what I ended up doing (via google):
[DllImport("user32.dll", EntryPoint = "SetWindowPos")]
public static extern bool SetWindowPos(
IntPtr hWnd, // window handle
IntPtr hWndInsertAfter, // placement-order handle
int X, // horizontal position
int Y, // vertical position
int cx, // width
int cy, // height
uint uFlags); // window positioning flags
public const uint SWP_NOSIZE = 0x1;
public const uint SWP_NOMOVE = 0x2;
public const uint SWP_SHOWWINDOW = 0x40;
public const uint SWP_NOACTIVATE = 0x10;
[DllImport("user32.dll", EntryPoint = "GetWindow")]
public static extern IntPtr GetWindow(
IntPtr hWnd,
uint wCmd);
public const uint GW_HWNDFIRST = 0;
public const uint GW_HWNDLAST = 1;
public const uint GW_HWNDNEXT = 2;
public const uint GW_HWNDPREV = 3;
public static void ControlSendToBack(IntPtr control)
{
bool s = SetWindowPos(
control,
GetWindow(control, GW_HWNDLAST),
0, 0, 0, 0,
SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE);
}
I get a handle to the installer window and then call ControlSendToBack() on it. It works, but it sends it to the very back. I tried another method that would just send it back one position, but this wouldn't work either. Windows programming--as good as it was in 1995. Cool.
Another way of doing this is to use a BackgroundWorker. You let the Background Worker handle the downloading of the file so it doesn't prevent the UI being updated.
See this link on donnetperls

Categories