Use Windows API in C # (reproduced)

xiaoxiao2021-03-06  42

Transfer from the Self-inviting discussion group http://www.fawcette.com/china/club/browse.aspx?id=140 The following is a basic process of calling the API as an example: Dynamic Link Library Function of Dynamic Link Library Function Before use, it must be declared relative to VB, C # function declarations more commendable. After paste the API Viewer, you can use it directly, and the latter needs to do additional changes in parameters.

Dynamic Link Library Function Declaration Sections are generally composed of two parts of the following, one is a function name or an index number, and the other is the file name of the dynamic link library. For example, you want to call the Messagebox function in user32.dll, we must specify the name MessageBoxa or MessageBoxwwwa or MessageBoxwww, and library name user32.dll, we know that Win32 API has two versions of each of the functions involving strings and characters. The ANSI version of the single-byte character and the Unicode version of the double-byte character.

Here is an example of the API function call: [DllImport ( "KERNEL32.DLL", EntryPoint = "MoveFileW", SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)] public static extern bool MoveFile String SRC, STRING DST;

Where the entry point EntryPoint identification function is in the entry location of the dynamic link library, in an jurisded engineering, the original name and serial number entry point of the target function not only identifies a function of the interoperability boundary. Moreover, you can also map this entry point into a different name, that is, rename the function. Rename can bring all kinds of convenience to the call function, by renaming, on the one hand, we don't have to write to the function of the function, and it can also ensure consistent with the existing naming rules, allowing a function with different parameter types. Coexistence, more importantly, it simplifies the call to ANSI and Unicode versions. Charset is used to identify function calls, which is Unicode or ANSI version. Exactspelling = false will tell the compiler to make the compiler decide to use Unicode or ANSI version. For other parameters, please refer to MSDN online help.

In C #, you can declare a dynamic link library function through the name and serial number in the EntryPoint field, if the function name used in the method definition is the same as the DLL entry point, you don't need to display the declaration function in the EntryPoint domain. Otherwise, you must use the following attribute format to indicate a name and serial number.

[DLLIMPORT ("Dllname", entrypoint = "functionName")] [DLLIMPORT ("Dllname", entrypoint = "# 123")]

It is worth noting that you must add "#" before the number serial number: Example of replacing the Messagebox name with MsGbox:

[C #] using system.runtime.interopservices;

Public class win32 {[DLLIMPORT ("User32.dll", entrypoint = "messagebox")] public static extern int msgbox (int hwnd, string text, string capen, uint type);} Many jurisdictional link library functions expect you Ability to deliver a complex parameter type to a function, such as a user-defined structural type member or a class member defined by the jurisdiction, and you must provide additional information formatted this type to maintain the original layout and alignment of the parameters. . C # provides a StructLayOutAttribute class, which you can define your own formatted type. In the jurisdiction code, the formatted type is a structure or class member descriptions descriptions descriptions illustrated by RuctLayOutAttribute, which guarantees its internal member expected layout information. There are three options in the layout:

LayoutKind.automatic LayoutKind.automatic In order to improve efficiency allows the run state to reorder type members. Note: Never use this option to call unlicensed dynamic link library functions. LayoutKind.ExPlicit Sorting LayoutKind.SEQUENTIAL on the type member in the Fieldoffset property, LayoutKind.SEQUENTIAL is sorted by a type member that appears in the jurisdiction from the jurisdiction of the jurisdiction. The following examples below describe how to define a point and rectangle type in the jurisdiction and pass it to the PtinRect function in the user32.dll library as a parameter, the unlicensed prototype statement is as follows: BOOL PTIECT (Const Rect * LPRC, POINT PT); Note You must pass the Rect structural parameters by reference, because the function requires a RECT structure pointer.

[C #] using system.runtime.interopservices;

[Structlayout (layoutkind.sequential)] public struct points {public int x; public int y;}

[StructLayout (LayoutKind.Explicit] public struct Rect {[FieldOffset (0)] public int left; [FieldOffset (4)] public int top; [FieldOffset (8)] public int right; [FieldOffset (12)] public int bottom }

class Win32API {[DllImport ( "User32.dll")] public static extern Bool PtInRect (ref Rect r, Point p);} Similarly GetSystemInfo you can call the function information obtaining system: using System.Runtime.InteropServices; [StructLayout (LayoutKind. Sequential)] public struct SYSTEM_INFO {public uint dwOemId; public uint dwPageSize; public uint lpMinimumApplicationAddress; public uint lpMaximumApplicationAddress; public uint dwActiveProcessorMask; public uint dwNumberOfProcessors; public uint dwProcessorType; public uint dwAllocationGranularity; public uint dwProcessorLevel; public uint dwProcessorRevision;}

[DLLIMPORT ("kernel32")] static extern void getSysteminfo (Ref system_info psi); system_info psi = new system_info (); getSystemInfo (Ref psi);

The passage of a member is also as long as the class has a fixed class member layout, you can also pass a class member to a dynamic link library function that is not jurisdiction. The following example mainly shows how to pass a Sequential order definition MYSystemTime class to USER32. The DLL's getSystemTime function, the function of the function of the C / C is as follows:

void GetSystemTime (SYSTEMTIME * SystemTime); not passed value type, class is always passed by reference [C #] [StructLayout (LayoutKind.Sequential)] public class MySystemTime {public ushort wYear;. public ushort wMonth; public ushort wDayOfWeek; public ushort wDay; public ushort wHour; public ushort wMinute; public ushort wSecond; public ushort wMilliseconds;} class Win32API {[DllImport ( "User32.dll")] public static extern void GetSystemTime (MySystemTime st);} callback functions of: from Most dynamic link library functions are called in the jurisdiction, you only need to create a definition of the jurisdiction, and then call it, this process is very straightforward. If a dynamic link library function requires a function pointer as a parameter, you still need to do the following steps: First, you must refer to the documentation about this function, determine if this function needs a callback; second, you must be in the jurisdiction code Create a callback function; Finally, you can deliver a pointer to this function to the DLL function,.

The callback function and its implementation: The callback function is often used in the task needs to be repeatedly executed, such as enumeration functions, such as EnumFontFamilies in the Win32 API, Enumprinters, EnumWindows (Window Enumeration) functions. Below the window enumeration as an example, talk about how all windows existing in the system by calling the EnumWindow function

Divide a few steps: 1. Declaration of the reference function before implementation BOOL EnumWindows (WndenumProc LpenUnc, LParmam iParam) Obviously this function requires a callback function address as a parameter. 2. Create an jurisded callback function, this example statement For the representative type (delegate), that is, what we call, it has two parameters hWnd and lparam, the first parameter is a window handle, the second parameter is defined by the application, both parameters are integer . When this callback function returns a non-zero value, the indication is successful, and the ridge is hints, this example always returns the TRUE value for continuous enumeration. 3. Finally, create a representative object, and passed it as a parameter to the EnumWindows function, and the platform automatically converts the transformation into a function that can identify the callback format that can be identified.

[C #] using system.Runtime.Interopservices;

public delegate bool CallBack (int hwnd, int lParam); public class EnumReportApp {[DllImport ( "user32")] public static extern int EnumWindows (CallBack x, int y); public static void Main () {CallBack myCallBack = new CallBack ( EnumReportapp.report); Enumwindows (MyCallback, 0);} public static bool report (int hwnd, int lparam) {console.write ("window handle"); console.writeLine (hwnd); return true;}}}

Pointer type Parameter Pass: When the Windows API function is called, most of the functions use pointer to pass parameters, for a structural variable pointer, in addition to using the above class and structural methods, we can sometimes use array to pass parameters. Below this function gets the username Bool getUserName (LPTSTR LPBUFFER, // username buffer LPTWORD NSIZE //); [DLLIMPI32.DLL ", entrypoint =" getcomputername ", EXACTSPELING = false, SetLastError = true)] static extern bool GetComputerName ([MarshalAs (UnmanagedType.LPArray)] byte [] lpBuffer, [MarshalAs (UnmanagedType.LPArray)] Int32 [] nSize); this function takes two parameters, char * and INT *, because you must allocate a string buffer to accept string pointers, you can use String classes instead of this parameter type, of course, you can also declare a byte array to pass ansi string, and you can also declare a only one Long integer array of elements, using an array name as the second parameter. The above functions can be called as follows: byte [] str = new byte [20]; int32 [] len = new int32 [1]; len [0] = 20; getcomputername (str, len); messagebox.show (system.text); messagebox.show .Encoding.ascii.getstring (STR)); Finally, it is necessary to remind that each method must be in the file header before use: use system.Runtime.IinteropServices; the following is some of my supplements: 1. LPTSTR can Map For StringBuilder2. When Map, LPWORD, LPDWORD, etc. can not be added to Marshalas Attribute.3. Some need to declare the pointer type as INTPTR instead of REF; 4. Use Marshal.StructureTructure and Marshal.StructureToptr to help complete INTPTR and Structure. Conversion between; 5. You can refer to the declaration of the API used by MS (such as content in System.Windows.Forms.unsafenativeMethods). I hope that the above content will help everyone.

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

New Post(0)