Call Windows API and other process communication with C #

xiaoxiao2021-03-06  23

Keywords:

C #, API, FindWindow, FindWindowex, SendMessage, Process, Registration

In order to facilitate network management, the company uses IEEE 802.1x network access control, so you need to enter two login passwords each time, I have studied the password to help me with the second login with C #.

Design ideas: By calling some methods in the Windows API, the main use is the three functions of FindWindow, FindWindowEx, and SendMessage, loop through all the current windows, find the target window and the user name saved in a specific location. Password and domain information automatically fill in the input box, and then trigger the Button event, and finally the program itself exits.

Environment: In Windows 2000 Chinese Edition SP4, VS.NET 2003 Chinese Under Windows 2000 Chinese Under Test

Screenshot:

The specific design of this form is slightly said.

In order to use the Win32 API, you need to introduce the following namespace:

Using

System.Runtime.InteropServices;

There is also a need for a process and registry, so it is also necessary to introduce the following two namespaces:

Using

System.Threading;

Using

Microsoft.win32;

The following code is used to add a reference to the API:

DLL import

#region Dll Import [DllImport ( "User32.dll", EntryPoint = "FindWindow")] private static extern IntPtr FindWindow (string lpClassName, string lpWindowName); [DllImport ( "user32.dll", EntryPoint = "FindWindowEx")] private static extern IntPtr FindWindowEx (IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow); [DllImport ( "User32.dll", EntryPoint = "SendMessage")] private static extern int SendMessage (IntPtr hWnd, int Msg, IntPtr wParam, string lparam); #ndregion

The main use is these three ways, and I don't detail here, please refer to MSDN.

Some parameters that need to be used:

Const

int

WM_GETTEXT

=

0x000D

;

Const

int

WM_SETTEXT

=

0x000c

;

Const

int

WM_CLICK

=

0x00f5

;

From the name, you should understand what these parameters are specific, and these parameters can be found through the tool SPY supplied with VS.

Here is the core part of the entire program, find the form and operate it:

SearchWindow

#REGON SearchWindow Private INT SearchWindow () {int RetVal = 0; // Add a return value to determine if the operation is successfully // below these parameters can be found with STRING LPSZPARENTCLASS = "# 32770"; // Whole window Class name string lpszparentWindow = "Local Connection"; // Window Title String Lpszclass = "Edit"; // Need to find the class name of the sub-window, that is, the input box string lpszclass_submit = "button"; // Need to find Button Class name string lpszname_submit = "OK"; // Need to find the button String text = ""; INTPTR PARENTHWND = New INTPTR (0); INTPTR EDITHWND = New INTPTR (0); // Check the form, get Whole Form Parenwnd = FindWindow (LPSZPARENTCLASS, LPSZPARETWINDOW); // Determine if this form is effective if (! PARENTHWND.EQUALS (INTPTR.ZERO)) {// get User Name this child form, and set its content edithwnd = findWindowex (PARENTHWND, EDITHWND, LPSZCLASS, ""); if (! EdithWnd.Equals (INTPTR.ZERO)) {text = this.tbusername.text.trim (); // Call SendMessage method Set its contents SendMessage (EdithWnd, WM_SETTEXT, (Int Ptr) 0, Text); RetVal ;} // Get password this sub-form, and set its contents edithWnd = findwindowex (PARENTHWND, EDITHWND, LPSZCLASS, ""); if (! EdithWnd.Equals (INTPTR.ZERO) ) {Text = this.tbpassword.text.trim (); sendMessage (EDTHWND, WM_SETTEXT, (INTPTR) 0, Text); RetVal ;} // gets this sub-form, and sets its content edithWnd = FINDWINDOWEX ParenWnd, EdithWnd, Lpszclass, "");

If (! EdithWnd.Equals (INTPTR.ZERO)) {text = this.tbdomain.text.trim (); sendMessage (EdithWnd, WM_SETTEXT, (INTPTR) 0, Text); RetVal ;} // get button this form and trigger its Click event EdithWnd = FindWindowEx (ParenthWnd, EdithWnd, lpszClass_Submit, lpszName_Submit); (! EdithWnd.Equals (IntPtr.Zero)) if {SendMessage (EdithWnd, WM_CLICK, (IntPtr) 0, "0") RetVal ;}}} #ENDREGON Action Here, it is necessary to explain that when there are several class names in one form, that is, if there are three input boxes, these three The class name of the input box is an edit. The results of the lookup are from top to bottom. I don't know what to do can divide each different input box. Later, I can only find one to try it. I didn't expect it to be right. (Is there a number of ways?)

The above code is only applicable to the Chinese version of the operating system, because the names of the same form under different operating systems are different, I don't have the English version here, so there is no way to test.

In order to eliminate the troubles of manual input every time, I need to save this information to a specific file. When the user is running this program for the first time, I only need to enter it once, click Save, first Save this information to a file, then load the program itself into the system boot item, so the program can be started next time, then read the information from the file to complete the following operations.

Select the path to the file:

Private

String

Userpro

=

System.environment.GetenvironmentVariable (

"

Userprofile

"

);

Private

String

Path

=

System.Environment.GetenvironmentVariable ("UserProfile")

@ "

/ Local settings / autolog.ini

"

;

Events triggered by the Save button under the user point:

Button Submit Click

#region Button Submit Click private void btSubmit_Click (object sender, System.EventArgs e) {SaveData ();} private void SaveData () {try {// Save Data FileInfo obj = new FileInfo (PATH); if (obj.Exists) obj.Delete (); FileStream ofile = new FileStream (PATH, FileMode.Create); // Hidden the file File.SetAttributes (PATH, FileAttributes.Hidden); StreamWriter sw = new StreamWriter (ofile); // the user name and password And domain information writes file sw.writeline (this.tbusername.text); sw.writeline (this.tbdomain.text); sw.flush (); sw.close () @ // copy the current file to the specified location, then add the start OPATH = Application.Startuppath @ / login.exe "; string tpath = userpro @" / Local settings / login.exe "; if (file.exism (tpath)) File.Delete (tpath); File.Copy (opath, tpath); RegistryKey hklm = Registry.CurrentUser; RegistryKey run = hklm.CreateSubKey (@ "SOFTWARE / Microsoft / Windows / CurrentVersion / Run"); run.SetValue ( "AutoLogin ", tpath); // Last program exits MessageBox.show (" OK "," Information ", MessageBoxButtons.ok, MessageBoxicon.information; Application.exit ();} catch (exception ex) {messagebox.show (ex." ToString (), "Error", MessageBoxButtons.ok, MessageBoxicon.Error);}} #ENDREGION

In this case, the program can be verified from the file that has been stored from the file. The last thing to do is that you need to open a process to loop the method of the search to execute the above SearchWindow until you find the eligible window and successfully verify it, and this process needs to start with the procedure. We can add a method called loadData in the constructor, then perform specific read file information and startup processes in this method.

Of course, first define this process:

Private

Thread thread;

Then the method of loadData:

Load

#region Load private void LoadData () {// Load Data FileStream ofile = new FileStream (PATH, FileMode.OpenOrCreate); StreamReader sr = new StreamReader (ofile); this.tbUserName.Text = sr.ReadLine (); this.tbPassword .Text = sr.readline (); this.tbdomain.text = sr.readline (); sr.close (); ofile.close (); // thread start thread = new thread (New Threadstart (Watch)); thread .Isbackground = true; thread.start ();} private void watch () {// Loop Find this window until the success of While (TRUE) {Int i = this.searchWindow (); if (i == 4) Break ;} // Program exit and release resource Application.exit (); this.dispose (); this.close ();} #ENDREGION

Ok, I have been introduced here. Of course, there are still many places that need to be improved. For example, the password should be saved in the way. I am still in contact with C # calling Windows API. Many things are also obtained from online checking materials. If you are inadequate, please point out.

Posted on 2005-01-16

转载请注明原文地址:https://www.9cbs.com/read-68244.html

New Post(0)