Call Windows API functions in C #

zhaozj2021-02-16  56

Call Windows API functions in C #

For the call of the Windows system API function, it is sometimes essential in programming, and various programming languages ​​specifies the way the calls and interfaces, the calling methods in the C # language are as follows (the following programming environment is Visual Studio .NET):

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

Using system.Runtime.InteropServices;

In the class definition body, add a reference to the API in a static call, and the API calls below this article are:

///

/// Open and close the CD tray.

///

[DLLIMPORT ("Winmm.dll", entrypoint = "mciSendstring", charset = charset.auto)]

Public Static Extern Int McIndString (String LPSTRCOMMAND, STRING LPSTRRRNSTRING, INT URETURNLENGTH, INT HWNDCALLBACK);

///

/// Display and hide the mouse pointer.

///

[DLLIMPORT ("User32.dll", entrypoint = "showcursor", charset = charset.Auto)]

Public Static Extern Int Showcursor (int bshow);

///

/// Empty the recycle station.

///

[DLLIMPORT ("shell32.dll", entrypoint = "shemptyrecyclebin", charset = charset.auto)]

Public Static Extern long writtyrecyclebin (INTPTR HWND, STRING PSZROOTPATH, Long Dwflags);

///

/// Open the browser

///

[DLLIMPORT ("shell32.dll", entrypoint = "shellexecute", charset = charset.auto)]

Public Static Extern int Shellexecute (INTPTR HWND, STRING LPOPERATION, STRING LPFILE, STRING LPPARES, STRING LPDIRECTORY, INT NSHOWCMD);

///

/// Maximum window, minimize windows, normal size window;

///

[DLLIMPORT ("User32.dll", entrypoint = "showwindow", charset = charset.auto)]

Public Static Extern Int ShowWindow (INTPTR HWND, INT NCMDSHOW);

2. After having 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, and Apicalls refers to the class name created in the first step.

Open CD tray: long lngreturn = apicalls.mcisendstring ("set cdaudio door open", strreturn, 127, 0);

Close CD tray:

Long lngreturn = apicalls.mcisendstring ("Set CDAUDIO DOOR CLOSED", STRRETURN, 127, 0);

Display the mouse pointer in the application form:

Apicalls.showcursor (1);

Hide mouse pointers in the application form:

Apicalls.showcursor (0);

Empty recycle bin:

Apicalls.ShemptyRecyclebin (form.activeform.handle, "", 0x00000000);

Open the browser window, TextBox1.text indicates the URL address to access:

Long lngreturn = apicalls.shellexecute (form.activeform.handle, "open", textbox1.text, ",", 1);

Maximize windows:

Apicalls.ShowWindow (Form.Activeform.handle, 3);

Minimize windows:

Apicalls.ShowWindow (Form.Activeform.handle, 2);

Restore normal size window:

Apicalls.ShowWindow (Form.Activeform.handle, 1);

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

New Post(0)