Call Win32 API from. NET platform

Source: Internet
Author: User

Win32 API can directly control the core of Microsoft Windows, because application programming interface is the interface that Microsoft left for us to directly control windows. Want to play? It's too difficult.
C # it is very simple to use. Writing a program is like playing gongshu, sorry -_-! It is as simple as building blocks. Want to play? Haha, there is no way to directly control the core of windows.
Is there no perfect solution? Of course not! Otherwise, no one has bought Microsoft products. In fact, calling Win32 APIs from C # (or. NET platform) is still very simple ~~~~ Today, we will study it together.

I. Basic Knowledge
Win32 API is a function set of C language (note that C ++ is not a language, although C is a subset of C ++. The C # language is completely different from the C language (except for syntactically similar). Therefore, it may take some time to call the Win32 API of C language in C. First, we need to prepare some basic knowledge.
1. Where can Win32 API functions be stored?
Win32 API functions are the core of windows. For example, the forms, buttons, and dialogs we see depend on Win32 functions to draw on the screen. These controls (sometimes called components) these functions are used for user interaction with windows. Therefore, the Win32 API functions used to control these controls are called "User Interface Win32 APIs" (ui functions for short). There are also some functions, it is not used for interaction, such as managing processes running in the current system and monitoring the status of the hardware system ...... These functions have only one set, but can be called by all Windows programs (as long as the program has high permissions). In short, APIs are shared by the program. To enable all programs to share a set of APIS, Windows adopts the "Dynamic Link Library" approach. The reason for calling "Dynamic Link Library" is that the function library is called in a "pay-as-you-go" way, rather than a "don't need to be used" like a static Link Library ".
This is not easy to understand. It doesn't matter. Let's give a small example. We compared windows to a playground, and compared children playing in the playground to a program. A child may need to drink water while playing. We have two ways for the little guys to drink water: 1. provide each of the little guys with a kettle. If the little guys drink, they will drink the water they bring. 2. assign a water dispenser to the playground. Obviously, the second method is much better, which is reflected in three places. First, with a kettle, the little guy is not flexible and has a bad time (affecting the speed of the Program). Besides, this is just a kettle. What if I bring another lunch box? Slide, helmet, Band-Aid, gauze ...... AK-47 my God, if it's all, it's time to catch up with the US Army. So there is still a public "warehouse" in the amusement park for convenience, so that everyone can use it as needed (dynamic link ). Second, the little guys bring so many things that occupy many places in the playground, so that the playground is crowded and other children cannot enter (the large size of the program affects the performance of the program and system ). Third, if an item has been upgraded, for example, from one litre to two litre, then each of the little guys must go home for a new one (re-compile the program, the compiler links the new static library to the main body of the Program). In the second case, as long as the playground changes the model of the kettle in its own warehouse, then all the little guys have a large kettle at the same time. (Wukong! I'm not here for a while. Why are you losing something ?! It's not good to hit the kids ~~~~~)
Wukong is in a hurry, so I will not be confused ...... Er ...... Win32 API functions are stored in the core library files of the Windows system. These libraries are stored in the hard disk as. DLL files. The commonly used DLL files are user32.dll and kernel32.dll, and some other DLL files are also very important. We need to accumulate more experience in practice.
We know that Win32 API functions are stored in the DLL file, but the new problem comes again-how can we call them? These DLL files are written in C language. After the source code is compiled by the C language compiler, the files are stored in binary executable code, it's like an apple is packed in a jar after it is made into jam by a shredder-you can no longer tell which one is from your GF and which one is from your mom. To allow the program to use these functions, Microsoft also releases the system SDK when releasing each new operating system. Currently, the latest SDK is win2003 SP1, it is said that Vista is coming soon, And the UI APIs have been separated from the core library to improve system stability. The SDK contains some C header files (. these files describe the Win32 API functions in the core DLL files. # include "..... "commands are included in your program, and you can use these Win32 APIs. As for how the program is linked, it is beyond the scope of this article-and beyond my knowledge: d
Now, if you are a C language expert, you can use the Windows SDK to transfer windows! However, today we are talking about calling the Win32 API in the C # language. Now we know that the API functions are stored in the DLL dynamic link library file and how the C language calls them. What should we do with the C # language? C # language does not support C. H files. C # language also uses DLL dynamic link library, but these DLL are. net version, with "self-descriptive", that is, all functions in your stomach have been written in your metadata, and no additional one is needed. h file. Now we have found the key point of the problem: how to use the C # language on the. NET platform to call the DLL files on the Win32 platform. The answer is very simple: Use the dllimport feature.
Ii. Test the knife
Next, let's write a small program and try to use the C # language and the dllimport feature to call Win32 API.

Using system;
Using system. runtime. interopservices;
Class Program
{
[Dllimport ("user32.dll")]
Public static extern int MessageBox (int h, string M, string C, int type );

Static int main ()
{
MessageBox (0, "Hello Win32 API", "Essence of water", 4 );
Console. Readline ();
Return 0;
}
}

Create a C # console program, clear the code automatically generated by Vs, and copy the code above to compile and execute it. Let's analyze this program:
1. To use the dllimport feature (the feature is also a type), you must use this using system. runtime. interopservices;
, Import "RunTime-> interactive service ". Oh ~~~~ Isn't the interactive service at runtime a "Dynamic Link? Thanks to Microsoft!
2. Then we can create a dllimport class instance and bind the instance to the function we want to use. The "feature class" type is very strange-myclass MC = new myclass () is not used for manufacturing class instances. Instead, [feature class (parameter list)] is used; feature classes cannot exist independently. They must be used to modify other objects (in this example, a function is used to modify the latter). Different features can be used to modify classes, functions, variables, and so on; when a feature instance is compiled, it does not generate executable code, but is put into metadata for retrieval. In short, you remember that the feature class is very strange. If you want to know more, you can check msdn. If you are too lazy to check it, remember this first-understanding the law of inertia does not affect your learning to ride a bicycle. [Dllimport ("user32.dll")] indicates that the Win32 API function we want to use is in the user32.dll file. The problem comes again: How do I know which DLL file Many API functions are in? You can find this in msdn at root> Win32 and COM development> development guides> Windows API reference> Functions by category. On this page, you will see a lot of API categories, all of which are here. Open a category, such as dialog box. In the functions section, you will see many specific functions, including the MessageBox function used above. Click to enter. You will open the detailed explanation and usage of MessageBox. Its name, return value, and parameter type have a full view! I am also very familiar with English ~~~~ At the bottom of this page, you can see a small table with a "minimum dll version user32.dll", which means this function is in user32.dll.
3. The next step is our function. There are several key points for calling Win32 functions in C. First, the name must be exactly the same as that of the Win32 API. Second, in addition to the dllimport class modification, the function must be declared as public static extern. Third: it is also the most abnormal point. The return value and parameter type of the function must be exactly the same as that of the Win32 API! This is hard for this group of beginners-the Win32 Data Type is quite strange, such as what lpstr and what hinstance are all Xiami Dongdong? For your reference, my blog shows "exploring Windows data types-who are you?" For more information, see. In addition, I have extracted a table from msdn, which corresponds to the common Win32 Data Types and. NET platform data types:
Figure 2 Non-pointer Data Types

 

Win32 types specification CLR type
Char, int8, sbyte, char 8-bit signed integer system. sbyte
Short, short int, int16, short 16-bit signed integer system. int16
Int, long, long int, int32, long32, bool, int 32-bit signed integer system. int32
_ Int64, int64, Longlong 64-bit signed integer system. int64
Unsigned char, uint8, uchar, byte 8-bit unsigned integer system. byte
Unsigned short, uint16, ushort, word, Atom, wchar, _ wchar_t 16-bit unsigned integer system. uint16
Unsigned, unsigned int, uint32, ulong32, dword32, ulong, DWORD, uint 32-bit unsigned integer system. uint32
Unsigned _ int64, uint64, dwordlong, ulonglong 64-bit unsigned integer system. uint64
Float, float Single-precision floating point system. Single
Double, Long Double, double-precision floating point system. Double
In Win32 this type is an integer with a specially assigned meaning; in contrast, the CLR provides a specific type specified Ted to this meaning.

With these things, we can convert a Win32 API function into a C # function. Take the MessageBox function as an example (see the function table just given). Its Win32 prototype is as follows:

Int MessageBox (hwnd, maid );

Function Name: MessageBox will remain unchanged.
Return Value: the int value remains unchanged (both Win32 and C # are 32-bit integers)
Parameter table: h indicates handle. Generally, handld is a pointer type. The pointer type on the Win32 platform is stored in 32 bits. Therefore, it corresponds to an int type in C. However, since it is a pointer, there are no positive and negative points, and 32 bits should be used to save the value -- in this way, uint (unsigned 32-bit integer) is used) to correspond to the H type of Win32. However, int is subject to C # And. net CLR, and uint is only supported by C. net CLR support, so the int type is used honestly in this example. (Ele. Me ...... Stick to it ......)
As for the abbreviation of long pointer to constant string, it is a string. Therefore, the string type in C # is correct.
Modifier: The corresponding dllimport and public static extern are required.

After some tossing, the Win32 MessageBox function is packaged into a C # function that can be called:

[Dllimport ("user32.dll")]
Public static extern int MessageBox (int h, string M, string C, int type );

Let me explain the usefulness of the four parameters:
First: Who is the parent window of the pop-up MessageBox. This example does not exist, so it is 0, that is, "Null Pointer ".
Second: the content of MessageBox. In this example, it is "Hello Win32 API ".
Third: the title of MessageBox. In this example, the name of my blog-the true meaning of Water-should be forgotten.
Fourth: What is the button on MessageBox? If it is 0, there is only one OK. MessageBox is too short. You will not be able to see the four words "the true meaning of water, so I changed it to 4, so there are two buttons. These are available in msdn function usage. However, I recommend that you read another article titled EVOLUTION OF A Win32 program.
So far, although a sparrow is small, it has been poisoned ~~~ Sorry -_-! The program that calls Win32 API is analyzed. The principle is not difficult! It's enough for fresh graduates to win HR! The true knowledge is that you are proficient in using msdn, SDK,. NET Framework class library VC/VC. Believe me -- msdn + SDK + VC/C # is definitely enough to pack windows properly.
3. Is it really necessary?
Hey hey ...... Look at my face. I'm smiling! You are all fooled! Not all underlying Windows operating systems must call Win32 APIs ~~~~ (Where are the bricks !!!)
What I want to say is:. NET Framework is a good encapsulation of Win32 APIs. Most Win32 API functions have been encapsulated in various classes of. NET Framework class libraries. If Win32 API functions are pearls scattered on the ground. net Framework is to split these pearls into various drawers by type-remind me of my mom-I can always find them when my books are full of beds, as soon as she packed up, I couldn't find it again, so she was depressed. Alas ...... No way. Let's take a closer look at the. NET Framework class library. There will be a lot of surprises!
Finally, let's end our article with an example!
The example is as follows ~~~~~
A long time ago, I wrote a program for a company to control user logon. Before logon, the user cannot move the mouse out of the logon form because the mouse must be controlled, so I first remembered calling the cursor-related functions in the Win32 API-so no matter how many calls were made to the clipcursor () function in the Win32 API, the effect was good.
When I flipped through the. NET Framework class library two days ago, I found that the clip attribute of the system. Windows. Forms. cursor class is dedicated for this purpose! I almost lost my nose ...... Create a C # windows program by yourself, paste the following core code to the double-click event of the main form, and try it. The purpose of this example is to tell you: 1. the program that understands the class library directly determines the efficiency and quality of your programming-using the components in the class library is much faster and safer than what we create from the wheel. 2. Do not directly call Win32 API functions-that is not safe.

Private void form1_doubleclick (Object sender, eventargs E)
{
Rectangle r = new rectangle (this. Left, this. Top, this. Width, this. Height );
System. Windows. Forms. cursor. Clip = R;
}

Finally, you must be very curious about which Win32 APIs are encapsulated by the. NET Framework. Okay, and an article in msdn specifically lists these. The article is named Microsoft Win32 to Microsoft. NET Framework API map. Read this article by yourself.

This article Reprinted from the network base camp: http://www.qqview.com/Dev/DotNet/200721910470.Html

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.