C # System Application of mouse simulation technology and Automatic mouse operation

Source: Internet
Author: User
Tags message queue

Game program operation is just two--keyboard input control and mouse input control, almost all games use the mouse to change the position and direction of the character, this article is mainly about how to use C # call Windows API function to realize the function of mouse simulation operation. First, by combining FindWindow and FindWindowEx to find the button for the form, operate the mouse through the Setcursorpos or mouse_event function, and involve the use of Spy + + Tool to get information about a form message.

I. Introduction to WINDOWS API functions

. NET does not provide functions that alter the position of the mouse pointer, impersonate a single-machine operation, but can be implemented by invoking Windows API functions.
[DllImport ("User32.dll")]
static extern bool Setcursorpos (int x,int Y);
This function sets the position of the mouse where x and y are the absolute position relative to the upper-left corner of the screen.
[DllImport ("User32.dll")]
static extern void Mouse_event (Mouseeventflag flags,int dx,int dy,uint data,uintptr extraInfo);
The function can not only set the absolute position of the mouse pointer, but also set the position in relative coordinates.
Where the flags flag is set, specifying the click button and mouse action
. DX refers to the amount of movement that the mouse has moved along the x-axis absolute position or the last mouse event position. Dy refers to the absolute position along the Y axis or the number of moves since the last mouse event. Data if the flags are Mouse_ Wheel This value refers to the number of mouse wheel movements (otherwise 0), and the positive values move forward. EXTRAINFO specifies an additional 32-bit value associated with the mouse event.
[DllImport ("User32.dll")]
static extern IntPtr FindWindow (string strclass, string strwindow);
The function obtains a window handle based on the class name and window name, but the function cannot find child windows and is not case-sensitive. If you want to find a child window from a window, you need to use the FindWindowEx function.
[DllImport ("User32.dll")]
static extern IntPtr FindWindowEx (IntPtr hwndparent, IntPtr Hwndchildafter,
String strclass, String strwindow);
This function gets a handle to a window that matches the given string with the class name and window name of the window, starting with the next child window that is located after the given child window. where parameters
Hwnparent is the parent window handle to find the child window, and if the value is NULL, the function finds all child windows of the Desktop window as the parent window of the desktop window.
Hwndchildafter the child window handle, the lookup starts from the next child window in the z-order, and the child window must be a hwnparent direct child window instead of a descendant window, and if Hwnchildafter is null, the lookup starts from the first child window of the parent window.
Strclass A pointer to a null end string that specifies the class name or a member that identifies the class name string.
Strwindow a null end string that points to a specified window name (window caption). If null, all forms are fully matched.
return Value: If the function succeeds, the return value is a window handle with the specified class name and window name, and if the function fails, the return value is null.

two. Mouse Auto Click button and view mouse running track

first create a C # project, design the form as shown, and add the timer Time control:

and add the following code, Can realize mouse simulation technology and automatic operation Mouse:

Using system;using system.collections.generic;using system.componentmodel;using system.data;using System.Drawing; Using system.linq;using system.text;using system.threading.tasks;using system.windows.forms;//referencing the new namespace using  System.Runtime.InteropServices; Structlayoutnamespace mouseaction{public partial class Form1:form {public Form1 () {I        Nitializecomponent ();  }//struct-layout native location [StructLayout (layoutkind.sequential)] struct Nativerect {public int            Left            public int top;            public int right;        public int bottom;               }//Enumerate the enumerations as bit fields [Flags] enum Mouseeventflag:uint//Set the key value of the mouse action {Move = 0x0001,            Occurs mobile Leftdown = 0x0002,//left mouse button Leftup = 0x0004,//mouse release left button         Rightdown = 0x0008,//Mouse down right button Rightup = 0x0010,//Mouse release right button Middledown = 0x0020,Mouse down middle button middleup = 0x0040,//Mouse release middle button Xdown = 0x0080, XUp = 0x0100, W        Heel = 0x0800,//mouse wheel is moved virtualdesk = 0x4000,//Virtual Desktop Absolute = 0x8000}        Set mouse position [DllImport ("User32.dll")] static extern bool Setcursorpos (int X, int Y);            Set mouse keys and actions [DllImport ("User32.dll")] static extern void Mouse_event (mouseeventflag flags, int dx, int dy, UINT data, UIntPtr extraInfo); UIntPtr pointer multiple handle type [DllImport ("User32.dll")] static extern IntPtr FindWindow (string strclass, String Strwindow        ); The function gets a window handle that matches the window's Thunder and window name to the given string hwnparent=null from the desktop window looking for [DllImport ("User32.dll")] static extern IntPtr Findwin               Dowex (IntPtr hwndparent, IntPtr hwndchildafter, String strclass, string strwindow);        [DllImport ("User32.dll")] static extern bool GetWindowRect (HandleRef hwnd, out nativerect rect);   Defining variables     const int animationcount = 80;                    Private point endposition;        private int count;            private void Button1_Click (object sender, EventArgs e) {nativerect rect;            Gets the main form handle INTPTR Ptrtaskbar = FindWindow ("Windowsforms10.window.8.app.0.2bf8098_r11_ad1", null);                 if (Ptrtaskbar = = IntPtr.Zero) {MessageBox.Show ("No windows found!");            Return            }//Get Form "Button1" button IntPtr ptrstartbtn = FindWindowEx (Ptrtaskbar, IntPtr.Zero, NULL, "Button1");                if (ptrstartbtn = = IntPtr.Zero) {MessageBox.Show ("No button found!");            Return            }//Get form size GetWindowRect (new HandleRef (this, ptrstartbtn), out rect);            Endposition.x = (rect.left + rect.right)/2;            ENDPOSITION.Y = (rect.top + rect.bottom)/2; Judging click button if (checkbox1.checked)           {//select "View mouse running trajectory" this.count = Animationcount;            Movementtimer.start ();                } else {Setcursorpos (endposition.x, ENDPOSITION.Y);                Mouse_event (mouseeventflag.leftdown, 0, 0, 0, Uintptr.zero);                Mouse_event (mouseeventflag.leftup, 0, 0, 0, Uintptr.zero);            TextBox1.Text = String.Format ("{0},{1}", mouseposition.x, MOUSEPOSITION.Y);            }}//tick: Timer, the function private void Movementtimer_tick (object sender, EventArgs e) occurs whenever the time elapsed            int stepx = (endposition.x-mouseposition.x)/count;            int stepy = (ENDPOSITION.Y-MOUSEPOSITION.Y)/count;            count--;                if (count = = 0) {movementtimer.stop ();                Mouse_event (mouseeventflag.leftdown, 0, 0, 0, Uintptr.zero);            Mouse_event (mouseeventflag.leftup, 0, 0, 0, Uintptr.zero);            }TextBox1.Text = String.Format ("{0},{1}", mouseposition.x, MOUSEPOSITION.Y);        Mouse_event (Mouseeventflag.move, stepx, stepy, 0, Uintptr.zero); }    }}

Customize a dialog box at the same time, adding a button to run the result as shown:

You can see that the "Button1" button for the form "Form1" is found through the FindWindow and FINDWINDOWEX functions when the program is checked to "view the mouse running track" and the "Start" button is clicked, and Mouse_ The event moves the mouse and clicks the mouse. Where the function prototype is:

IntPtr FindWindowEx (    IntPtr hwndparent,     //Handle to parent window [parent form handle]    IntPtr hwndchildafter,//Handle T o child window [subform handle]    string strclass,       //class name [Form class name]    string Strwindow       //window name [form name]);

But how to find the class name of the form and the name of the button? As a beginner, many forms I have not implemented such as QQ, it needs to use a tool called Spy + +.
PS: The first time to make GIF format dynamic pictures, refer to the blog http://blog.csdn.net/tangcheng_ok/article/details/8246792

three. Get form information using the Spy + + tool

If the modified code is:

Get taskbar handle IntPtr ptrtaskbar = FindWindow ("Shell_traywnd", null); Pallet notification handle INTPTR PTRSTARTBTN = FindWindowEx (Ptrtaskbar, IntPtr.Zero, "Traynotifywnd", null);  

You can get the tray notification handle for the taskbar on the bottom of your computer, which is found in the Spy + + tool (vs. tools in the tool), as shown in:

Similarly, I get the txt handle through the Spy + + tool, first open the Spy + + tool, click the "Find Window" button (telescope), and then click on the "Finder Tool" button to drag and drop to the form you want to view, click the "OK" button.

This displays the TXT message, and you can right-click Properties to display the form's class name, form title, handle, and so on.

Finally, the hello.txt handle can be obtained by the following code:

Gets the Notepad handle IntPtr Ptrtaskbar = FindWindow ("Notepad", null); IntPtr ptrstartbtn = FindWindowEx (Ptrtaskbar, IntPtr.Zero, " Edit ", NULL);

The mouse is then manipulated through the mouse_event, and the specified message can be sent to one or more windows by SendMessage, and the PostMessage sends a message to a thread's message queue and returns immediately. Implement messaging and other functions to learn ing~

Four. Summary

This article mainly describes how C # operation mouse events, in the production of the game plug-in or automatically run the program is very useful, but unfortunately, the form name "Form1" to get the form is always unsuccessful, you need to get its class name through Spy + + to achieve. Why? At the same time if you want to learn keyboard simulation technology can study SetWindowsHookEx (installation hooks), CallNextHookEx (Next hook), UnhookWindowsHookEx (unloading hooks) and mouse hook to implement a lot of technology.
Hope the article is helpful to everyone, if there are errors or shortcomings, please forgive ~
(By:eastmount October 13, 2014 Night 8 o'clock
http://blog.csdn.net/eastmount/)
References-Online notes:
This paper mainly refers to the book "C # Network into a high-level chapter of the Web game Programming" Zhanghuibin Wang Xiaofeng
1.c# get the content of QQ chat input box
http://www.csharpwin.com/csharpspace/9133r5654.shtml
2.c# Find window, FindWindow usage (BY-LYBWWP)http://blog.csdn.net/lybwwp/article/details/8168553
3.FindWindowEx Usage (by-coolszy)http://blog.csdn.net/coolszy/article/details/5523784
4.c# Hide taskbar start button close Shell (BY-SSHHBB)http://blog.csdn.net/sshhbb/article/details/6605976
5. Taskbar handlehttp://blog.csdn.net/wangjieest/article/details/6943241
6.c# How to automatically enter a password in an external program's Password boxhttp://biancheng.dnbcw.info/c/117849.html
7.c# Implementing call Operations on external programshttp://www.blue1000.com/bkhtml/c17/2012-11/70993.htm
8. Baidu knowsC # API function FindWindowEx Returns the value of a subform to zero
9. Baidu knowsUse the C # action API to fill the textbox inside the desktop and click the form button

C # System Application of mouse simulation technology and Automatic mouse operation

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.