C # call API to send data to external programs

Source: Internet
Author: User

C # call API to send data to external programs

It is possible to do a project recently. In the project has such a function, in a program to invoke the B program, while in a program login, a program to the login name and password to automatically fill in the B Program Login dialog box, so that the B program does not need to enter a user name and password, simplifying the operation of operators. Just recently idle nothing, just how to think how to achieve. After two days of tossing and finishing, basically completed the implementation of the above functions. The following will be the implementation method, the process with everyone to share.

First, the principle

To implement these functions, you need to call the win API to implement. The Win32 API is the application programming interface for Microsoft 32-bit platforms (application programming Interface). These functions can be called by all applications running on the Win32 platform.

Then in the implementation of this program, we need to use the following three API functions (function descriptions are found from the Internet, easy to see), as well as write a findwindowbyindex function.

1, static extern int SendMessage1 (INTPTR hwnd, uint wmsg, int wParam, int lParam);

As the name implies, the function of the SendMessage function is "send Message", which will send a message to the specified object (operating system, window or control, etc.) to produce a specific action (such as scrolling, modifying the appearance of the object, etc.).

The meanings and descriptions of four of these arguments are as follows:

HWnd: The handle to the object. If you want to pass the message to which object, the handle of the object is passed as an argument.

WMSG: The message being sent. Depending on the specific needs and different objects, different messages are routed as arguments to produce the expected action.

WParam, LParam: Additional message information. These two are optional arguments to provide more information about the WMSG message, and the different wmsg may use 0, 1, or 2 of the two parameters, and if no additional parameter is required, the argument is assigned null (0 in VB).

2, public static extern IntPtr FindWindow (string className, string windowname);

The FindWindow function returns the window handle to the topmost window of the window class name or window name that matches the specified character creation. This function does not look for child windows.

Lpclassname: Pointer to a null-terminated string that specifies the class name or an atom that can determine the class name string. If this argument is an atom, then it must be a global atom that has been created by the Globaladdatom function before calling this function. This atom (a 16bit value) must be placed in the low byte of the lpclassname, and the high byte of the Lpclassname is zeroed.

Lpwindowname: Pointer to a null-terminated string that specifies the window name (that is, the window caption). If this parameter is null, all window names are matched.

Return value: If the function executes successfully, the return value is the handle to the window that owns the specified window class name or window name. If the function execution fails, the return value is NULL. You can get more detailed error information by calling the GetLastError function.

3, static extern IntPtr FindWindowEx (IntPtr hwndparent, IntPtr hwndchildafter, String lpszclass, string lpszwindow);

Looks for the first child window in the window list that matches the specified criteria. The function obtains a handle to a window that matches the given string with the class name and window name. This function finds the child window, starting at the next subwindow that follows the given child window. is not case-sensitive when searching.

hWndParent: The handle of the parent window where the child window is to be found (if hWndParent is set, the child window is searched from the parent window that the hwndparent points to). If hWndParent is 0, the function finds all child windows of the Desktop window as the parent window of the desktop window. Windows NT5.0 and later: If hWndParent is Hwnd_message, the function only looks for all message windows.

Hwndchildafter: child window handle. The lookup starts with the next child window in the Z-order. The child window must be a direct child window of the hWndParent window, not a descendant window. If Hwndchildafter is null, the lookup starts at the first child window of hwndparent. If hwndparent and hwndchildafter are null at the same time, the function finds all the top-level windows and the message window.

Lpszclass: A pointer to an empty end string that specifies the class name, or a member that identifies the class name string. If the parameter is a member, it must be the global member produced by the previous call to the Theglobaiaddatom function. The member is 16 bits and must be in the low 16 bits of the lpclassname and the high must be 0.

Pszwindow: Points to an empty end string that specifies the window name (window caption). If the parameter is NULL, all Windows match.

Return value: Long, the handle of the found window. If no matching window is found, zero is returned. Set GetLastError if the function succeeds, the return value is the window handle with the specified class name and window name. If the function fails, the return value is null.

4, Static IntPtr Findwindowbyindex (IntPtr hwndparent, int index)

The function finds the appropriate control by means of an implied index.

The function source code is as follows:

Static IntPtr Findwindowbyindex (IntPtr hwndparent, int index)

{

if (index = = 0)

return hwndparent;

Else

{

int ct = 0;

INTPTR result = IntPtr.Zero;

Do

{

result = FindWindowEx (hwndparent, result, NULL, NULL);

if (Result! = IntPtr.Zero)

++CT;

} while (CT < index && result! = IntPtr.Zero);

return result;

}

}

Second, the API call method (Note: This paragraph text extracts from the Internet)

1, use the corresponding namespace using System.Runtime.InteropServices;

2, using the DllImportAttribute feature to introduce API functions, notice that the empty method is declared, that is, the method body is empty.

[DllImport ("User32.dll")]

public static extern returntype functionname (type arg1,type arg2,...);

Call is not different from calling other methods

You can use fields to further illustrate attributes, separated by commas, such as: [DllImport ("kernel32", entrypoint= "GetVersionEx")]

The public fields of the DllImportAttribute feature are as follows:

1. CallingConvention indicates the CallingConvention value used when passing method parameters to an unmanaged implementation. CALLINGCONVENTION.CDECL: The caller cleans up the stack. It enables you to invoke a function that has varargs. Callingconvention.stdcall: The callee cleans up the stack. It is the default convention for calling unmanaged functions from managed code.

2. CharSet controls the name version of the calling function and indicates how to marshal the String parameter to the method.

This field is set to one of the CharSet values. If the CharSet field is set to Unicode, all string parameters are converted to Unicode characters before being passed to the unmanaged implementation. This also causes the letter "W" to be appended to the name of the DLL entrypoint. If this field is set to ANSI, the string is converted to an ANSI string, and the letter "A" is appended to the name of the DLL entrypoint. Most Win32 APIs Use this convention to append "W" or "a". If CharSet is set to Auto, this conversion is platform-related (Unicode on Windows NT, Ansi on Windows 98). The default value for CharSet is Ansi. The CharSet field is also used to determine which version of the function will be imported from the specified DLL. The name matching rules for CharSet.Ansi and CharSet.Unicode are very different. For Ansi, if EntryPoint is set to "MyMethod" and it exists, then "MyMethod" is returned. If there is no "MyMethod" in the DLL, but "Mymethoda" is present, then "Mymethoda" is returned. The opposite is true for Unicode. If EntryPoint is set to "MyMethod" and it exists, then "Mymethodw" is returned. If "Mymethodw" is not present in the DLL, but "MyMethod" is present, then "MyMethod" is returned. If you are using Auto, the matching rules are platform-related (Unicode on Windows NT, Ansi on Windows 98). If ExactSpelling is set to True, "MyMethod" is returned only if "MyMethod" is present in the DLL.

3. entrypoint indicates the name or ordinal of the DLL entry point to invoke.

If your method name does not want to have the same name as the API function, be sure to specify this parameter, for example:

[DllImport ("User32.dll", charset= "CharSet.Auto", entrypoint= "MessageBox")]
public static extern int MsgBox (intptrhwnd,string txt,string caption, int type);

4. ExactSpelling indicates whether the name of the entry point in the unmanaged DLL should be modified to correspond to the CharSet value specified in the CharSet field. If true, when the DllImportAttribute.CharSet field is set to CharSet ANSI value, the letter A is appended to the method name when the DllImportAttribute.CharSet field is set to CharSet Unicode value, the letter W is appended to the name of the method. The default value for this field is false.

5. PreserveSig indicates that the managed method signature should not be converted to a return HRESULT, and there may be an unmanaged signature that corresponds to the return value of the attached [out, retval] parameter.

6. SetLastError indicates that the callee will call the Win32 API SetLastError before returning from the attributed method. True indicates that the caller will call SetLastError, which defaults to false. The runtime marshaler calls GetLastError and caches the returned value in case it is overridden by another API call. The user can retrieve the error code by calling GetLastWin32Error.

Third, procedure realization process

Program A: Two text boxes with a Start button. Two text boxes are used to enter a user name and password, and the Start button is used to start program B.

Program B: Two text boxes to accept the string that program a sends over.

1, a program code list is as follows:

Using System.Runtime.InteropServices;

Using System.Threading;

Private staticSystem.Diagnostics.Process p;

[DllImport ("user32.dll", EntryPoint = "SendMessage", CharSet = CharSet.Unicode)]

static extern int SendMessage1 (Intptrhwnd, uint wmsg, intwparam, int lParam);

[DllImport ("user32.dll", EntryPoint = "FindWindow", SetLastError = true, CallingConvention = Callingconvention.winapi, CharSet = CharSet.Unicode)]

public static extern Intptrfindwindow (string className, string windowname);

[DllImport ("user32.dll", EntryPoint = "FindWindowEx", CharSet = CharSet.Auto)]

static extern IntPtr FindWindowEx (intptrhwndparent, IntPtr hwndchildafter, String lpszclass, Stringlpszwindow);

Static Intptrfindwindowbyindex (IntPtr hwndparent, int index)

{

if (index = = 0)

Returnhwndparent;

Else

{

INTCT = 0;

Intptrresult = IntPtr.Zero;

Do

{

Result =findwindowex (hwndparent, result, NULL, NULL);

if (Result! = IntPtr.Zero)

++CT;

} while (CT < index && result! = IntPtr.Zero);

Returnresult;

}

}

2. Start button Event code

Privatevoid button4_click (Objectsender, EventArgs e)

{

if (p = = null)

{

p = newSystem.Diagnostics.Process ();

p.StartInfo.FileName = "b program path";

P.start ();

The thread must be suspended for a certain amount of time, otherwise the string cannot be sent automatically past.

Thread.Sleep (500);

Intptrparenthwnd = new IntPtr (0);

INTPTRPP = new IntPtr (0);

Intptrmwh = IntPtr.Zero;

Get window by Window caption

Parenthwnd = FindWindow (null, "******");

The index is obtained by retrieving the text edit box for the B program, retrieving the ID of the control by index, then converting the ID to 16, and comparing it with Spy + + to see the ID, thus determining the index of the control.

Intptrbutt = Findwindowbyindex (Parenthwnd, 5);

Uintwm_char = 0x0102;

SendMessage1 each time a string is sent, so the full user name is sent through a loop

foreach (char c in This.textBox1.Text)

{

SendMessage1 (Butt, WM_CHAR, C, 0);

}

Get Password entry box

INTPTRBUTT1 = Findwindowbyindex (Parenthwnd, 3);

Send password

foreach (char c in This.textBox2.Text)

{

SendMessage1 (BUTT1, WM_CHAR, c,0);

}

}

Else

{

if (p.hasexited)//is running {

P.start ();

}

}

3. Program Operation result

After clicking Start, in the second program (front), get the user name and password sent to the first program directly.

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.