C # API to maximize and minimize a specified window

Source: Internet
Author: User

Address: http://chfydemail.blog.163.com/blog/static/3411336420082193333905/

 

Implementation of Calling Windows API functions in C #
 
 
The call of API functions in Windows is sometimes essential in programming. Various programming languages have standardized the calling methods and interfaces, the calling method in C # is as follows (the following programming environment is Visual Studio. net ):

1. Add a new class item to the project, open the class file, and add a reference to the following namespace in the file header:

Using system. runtime. interopservices;

In the class definition subject, the reference to the API is added to the static call method. The following API call is used as an example:

/// <Summary>

/// Open and close the CD tray.

/// </Summary>

[Dllimport ("winmm. dll", entrypoint = "mcisendstring", charset = charset. Auto)]

Public static extern int mcisendstring (string lpstrcommand, string lpstrreturnstring, int ureturnlength, int hwndcallback );

/// <Summary>

/// Display and hide the mouse pointer.

/// </Summary>

[Dllimport ("user32.dll", entrypoint = "showcursor", charset = charset. Auto)]

Public static extern int showcursor (INT bshow );

 

/// <Summary>

/// Clear the recycle bin.

/// </Summary>

[Dllimport ("shell32.dll", entrypoint = "shemptyrecyclebin", charset = charset. Auto)]

Public static extern long shemptyrecyclebin (intptr hwnd, string pszrotpath, long dwflags );

 

/// <Summary>

/// Open the browser

/// </Summary>

[Dllimport ("shell32.dll", entrypoint = "ShellExecute", charset = charset. Auto)]

Public static extern int ShellExecute (intptr hwnd, string lpoperation, string lpfile, string lpparameters, string lpdirectory, int nshowcmd );

 

/// <Summary>

/// Maximize the window, minimize the window, normal size window;

/// </Summary>

[Dllimport ("user32.dll", entrypoint = "showwindow", charset = charset. Auto)]

Public static extern int showwindow (intptr hwnd, int ncmdshow );

 

 

2. With the above file, you can call the above API in the event processing of your own form object. The method is as follows:

The following strreturn is a public variable of the string type. apicils refers to the class name created in the first step.

Open the CD tray:

Long lngreturn = apicils. mcisendstring ("set cdaudio door open", strreturn, 127, 0 );

Close the CD tray:

Long lngreturn = apicils. mcisendstring ("set cdaudio door closed", strreturn, 127, 0 );

Show the mouse pointer in the application form:

Apicwalls. showcursor (1 );

Hide the mouse pointer in the application form:

Apicwalls. showcursor (0 );

Clear the recycle bin:

Apicils. shemptyrecyclebin (Form. activeform. Handle, "", 0x00000000 );

Open the browser window. textbox1.text indicates the URL to be accessed:

Long lngreturn = apicils. ShellExecute (Form. activeform. Handle, "open", textbox1.text, "", "", 1 );

Maximum window:

Apicwalls. showwindow (Form. activeform. Handle, 3 );

Minimize window:

Apicwalls. showwindow (Form. activeform. Handle, 2 );

Restore normal size window:

 

Apicwalls. showwindow (Form. activeform. Handle, 1 );
Open the browser window. textbox1.text indicates the URL to be accessed:

Long lngreturn = apicils. ShellExecute (Form. activeform. Handle, "open", textbox1.text, "", "", 1 );

Maximum window:

Apicwalls. showwindow (Form. activeform. Handle, 3 );

Minimize window:

Apicwalls. showwindow (Form. activeform. Handle, 2 );

Restore normal size window:

Apicwalls. showwindow (Form. activeform. Handle, 1 );

 

 
In the. NET Framework SDK documentation, the instructions for calling Windows APIs are scattered, and a little more comprehensive is about Visual Basic. net. In this article, the main points of calling APIs in C # are summarized as follows, hoping to help those who have not used APIs in C. In addition, if Visual Studio is installed. in C:/program files/Microsoft Visual Studio. net/frameworksdk/samples/technologies/InterOP/platforminvoke/winapis/CS directory contains a large number of API call examples.

I. Call format

Using system. runtime. interopservices; // reference this namespace to simplify the subsequent Code

 

...

 

// Use the dllimportattribute feature to introduce API functions. Note that empty methods are declared, that is, the method body is empty.

 

[Dllimport ("user32.dll")]

 

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

 

// There is no difference between calling and calling other methods

You can use fields to further describe features and separate them with commas, for example:

 

[Dllimport ("Kernel32", entrypoint = "getversionex")]

 

The common fields of the dllimportattribute feature are as follows:

 

1. callingconvention indicates the callingconvention value used to pass method parameters to an unmanaged implementation.

Callingconvention. cdecl: The caller clears the stack. It enables you to call functions with varargs.

 

Callingconvention. stdcall: the called party clears the stack. It is the default convention for calling unmanaged functions from managed code.

 

 

 

2. charset controls the name version of the called function and indicates how to mail 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 an unmanaged implementation. This also causes the name of the DLL entrypoint to be appended with the letter "W ". If this field is set to ANSI, the string is converted to an ANSI string and the name of the DLL entrypoint is appended with the letter "". Most Win32 APIs use this APPEND "W" or "A" convention. If charset is set to Auto, the conversion is platform-related (Unicode on Windows NT and ANSI on Windows 98 ). The default value of charset is ANSI. The charset field is also used to determine which function version 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, "mymethod" is returned ". If the DLL does not contain "mymethod", but "mymethoda" exists, "mymethoda" is returned ". The opposite is true for Unicode. If you set entrypoint to "mymethod" and it exists, "mymethodw" is returned ". If "mymethodw" does not exist in the DLL but "mymethod" exists, "mymethod" is returned ". If auto is used, the matching rule is related to the platform (Unicode on Windows NT and ANSI on Windows 98 ). If exactspelling is set to true, "mymethod" is returned only when "mymethod" exists in the DLL ".

 

 

 

3. entrypoint indicates the name or serial number of the DLL entry point to be called.

 

 

 

If you do not want the method name to be the same as the API function name, you must specify this parameter. For example:

 

[Dllimport ("user32.dll", charset = "charset. Auto", entrypoint = "MessageBox")]

 

Public static extern int msgbox (intptr hwnd, string txt, string caption, int type );

 

 

 

4. exactspelling indicates whether to modify the name of the entry point in the unmanaged DLL to correspond to the charset value specified in the charset field. If this parameter is set to true, the parameter is set to dllimportattribute. when the charset field is set to the ANSI value of charset, append the letter A to the method name, when dllimportattribute. when the charset field is set to the Unicode value of charset, W is appended to the method name. The default value of this field is false.

 

 

 

5. preservesig indicates that the signature of the managed method should not be converted to an unmanaged signature that returns hresult and may have an additional [out, retval] parameter corresponding to the returned value.

 

 

 

6. setlasterror indicates that the called party will call the Win32 API setlasterror before returning the property method. True indicates that the caller calls setlasterror. The default value is false. Getlasterror will be called by the mail collector during runtime and the returned value will be cached to prevent it from being overwritten by other API calls. You can call getlastwin32error to retrieve the error code.

 

 

 

Ii. Parameter type:

 

 

 

1. You can use the corresponding numeric type directly. (DWORD-> int, word-> int16)

 

 

 

2. String pointer type in API-> string in. net

 

 

 

3. Handle (DWORD) in API> intptr in. net

 

 

 

4. Structure in API>. net structure or class. Note that in this case, the structlayout feature should be used to limit the declared structure or Class

 

 

 

The Common Language Runtime library uses structlayoutattribute to control the physical layout of data fields of a class or structure in the managed memory, that is, the class or structure needs to be arranged in a certain way. If you want to pass the class to the unmanaged code that requires the specified layout, it is important to explicitly control the class layout. Its constructor uses the layoutkind value to initialize a new instance of the structlayoutattribute class. Layoutkind. Sequential is used to force members to be laid out in the order they appear.

 

 

 

Layoutkind. Explicit is used to control the exact location of each data member. With explicit, each member must use fieldoffsetattribute to indicate the position of this field in the type. For example:

 

[Structlayout (layoutkind. explicit, size = 16, charset = charset. ANSI)]

 

Public class mysystemtime

 

{

 

[Fieldoffset (0)] public ushort wyear;

 

[Fieldoffset (2)] public ushort wmonth;

 

[Fieldoffset (4)] public ushort wdayofweek;

 

[Fieldoffset (6)] public ushort wday;

 

[Fieldoffset (8)] public ushort whour;

 

[Fieldoffset (10)] public ushort wminute;

 

[Fieldoffset (12)] public ushort wsecond;

 

[Fieldoffset (14)] public ushort wmilliseconds;

 

}

 

 

 

The following is an example of defining the corresponding class or structure in. net for the osversioninfo structure in the API:

 

/*************************************** *******

 

* Define the original structure declaration in the API

 

* Osversioninfoa struct

 

* Dwosversioninfosize DWORD?

 

* Dwmajorversion DWORD?

 

* Dwminorversion DWORD?

 

* Dwbuildnumber DWORD?

 

* Dwplatformid DWORD?

 

* Szcsdversion byte 128 DUP (?)

 

* Osversioninfoa ends

 

*

 

* Osversioninfo equ <osversioninfoa>

 

**************************************** *****/

 

 

 

//. NET is declared as a class

 

[Structlayout (layoutkind. Sequential)]

 

Public class osversioninfo

 

{

 

Public int osversioninfosize;

 

Public int majorversion;

 

Public int minorversion;

 

Public int buildnumber;

 

Public int platformid;

 

 

 

[Financialas (unmanagedtype. byvaltstr, sizeconst = 128)]

 

Public String versionstring;

 

}

 

// Or

 

// The Declaration in. Net is a structure

 

[Structlayout (layoutkind. Sequential)]

 

Public struct osversioninfo2

 

{

 

Public int osversioninfosize;

 

Public int majorversion;

 

Public int minorversion;

 

Public int buildnumber;

 

Public int platformid;

 

 

 

[Financialas (unmanagedtype. byvaltstr, sizeconst = 128)]

 

Public String versionstring;

 

}

 

 

 

In this example, the mashalas feature is used to describe the sending format of fields, methods, or parameters. Use it as the parameter prefix and specify the data type required by the target. For example, the following code uses two parameters as the long pointer of the Data Type to block the string (lpstr) sent to the Windows API function ):

 

[Financialas (unmanagedtype. lpstr)]

 

String existingfile;

 

[Financialas (unmanagedtype. lpstr)]

 

String newfile;

 

 

 

Note that when the structure is used as a parameter, the ref modifier must be added before. Otherwise, an error occurs: the object reference does not include an instance of the specified object.

 

[Dllimport ("Kernel32", entrypoint = "getversionex")]

 

Public static extern bool getversionex2 (ref osversioninfo2 osvi );

 

 

 

3. How can we ensure that the platform with managed objects is successfully called?

 

 

 

If the hosted object is not referenced anywhere after the platform invoke is called, The Garbage Collector may complete the hosted object. This will release the resource and make the handle invalid, resulting in platform invoke call failure. Using handleref to wrap the handle ensures that the hosted object is not garbage collected before the platform's invoke call is complete.

 

 

 

For example:

 

Filestream FS = new filestream ("a.txt", filemode. Open );

 

Stringbuilder buffer = new stringbuilder (5 );

 

Int READ = 0;

 

Readfile (FS. Handle, buffer, 5, out read, 0); // call the readfile function in the win api

 

 

 

Because FS is a hosted object, it may be reclaimed by the spam Recycle Bin before the platform call is complete. After packaging the file stream handle with handleref, you can avoid being recycled by the garbage station:

 

[Dllimport ("kernel32.dll")]

 

Public static extern bool readfile (

 

Handleref hndref,

 

Stringbuilder buffer,

 

Int numberofbytestoread,

 

Out int numberofbytesread,

 

Ref overlapped flag );

 

......

 

......

 

Filestream FS = new filestream ("handleref.txt", filemode. Open );

 

Handleref hR = new handleref (FS, FS. Handle );

 

Stringbuilder buffer = new stringbuilder (5 );

 

Int READ = 0;

 

// Platform invoke will hold reference to handleref until call ends

 

Readfile (HR, buffer, 5, out read, 0 );

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.