C # and Win32 API calls

Source: Internet
Author: User

= = Reprint = = Liu Tieno
Date: 2005-12-20
Keywords: C #. NET Win32 API Small Order
The Win32 API can directly control the core of Microsoft Windows because the API (application programming Interface) is the interface that Microsoft left us to control windows directly. You want to play? Oh, it's too hard.
C # is very simple to use, write programs like arch pigs, Sorry-_-! , as simple as building blocks. You want to play? Oh, there is no way to directly control the core of Windows.
Isn't there a way to get the most out of it? Of course not! Otherwise, Microsoft's product has no one to buy already. actually from C # (or. NET platform) Call Win32 API or very simple drip ~ ~ ~ Today we all come together to study.

I. Basic knowledge
The Win32 API is the C language (note, not the C + + language, although C is a subset of the C + + language) function set. The C # language is completely different from the C language(in addition to grammatical comparisons), it takes a while to invoke the C language Win32 API in C #. First, we need to prepare some basic knowledge.
1. Where is the Win32 API function placed?
The Win32 API function is the core of windows, such as the forms, buttons, dialogs, and so on that we see, all relying on the Win32 function to "draw" on the screen, because these controls (sometimes called components) are used by the user to interact with Windows, so controlling the Win32 of those controls The API functions are called "User Interface" functions (Interface Win32 API), or UI functions, and there are functions that are not used for interaction, such as managing processes running on the current system, monitoring the state of hardware systems, etc... These functions have only one set, but can be called by all Windows programs (as long as the permissions of the program are high enough), in short, the API is shared by the program. To achieve the purpose of sharing a set of APIs for all programs, Windows uses a "dynamic link library" approach. It is called a "dynamic link library" because such libraries are called "hop-on-take" rather than "take it with no need" like a static-link library.
It's not good to understand, it doesn't matter, let's give a small example. We make Windows a playground, and the children playing in playgrounds are more than a program. Children may have to drink in the process of playing. We have two ways to get the kids to drink water when they want it. 1. Give each little one a kettle, and the little ones drink the water they bring with them; 2. Give the amusement park a water dispenser, who is thirsty who will drink it. Obviously, the second method is much better, which is reflected in three places. First, with a kettle, the little guy is not flexible, play (affect the speed of the program), and this is just a kettle, if you bring a lunch box? There are roller skating, helmets, band-post, gauze ... AK-47 My God, if you bring them all, catch up with US soldiers. So the amusement park still has a public "storehouse" to come of convenient, let everybody follow with take (dynamic link). Second, the little ones with so many things, occupy the playground a lot of places, so that the playground is overcrowded, other children will not enter (program size, affect the program and system performance). Third, if an item is upgraded, such as a kettle changed from one liter to two liters, then each of the little ones must go home for a new one (recompile the program, the compiler will link the new static library into the program body), and in the second case, as long as the playground to the water bottle in their warehouse for a model, then all the little guys are At the same time has a large capacity of the kettle. (Goku!) I'll be away for a while, why are you throwing things away? How bad it is to hit a little ~~~~~)
Wukong has been anxious, I will no longer Ji-ji crooked ... Uh...... WIN32 API functions are placed in the core library files of the Windows system, which are stored as. dll files on the hard disk. The DLL files that we commonly use are user32.dllAnd Kernel32.dllTwo files, and some other DLL files are also very important, we have to accumulate experience in practice.
We know that the Win32 API functions are placed in DLL files, but new problems are coming-how do we call them? These DLL files are written in C, and the source code is compiled in the C language compiler and stored in these DLL files as binary executable code, as if the apple were crushed into a jam and placed in a jar-you never know which one your GF gave you, and which one your mother gave you. In order for the program to use these functions, Microsoft releases the SDK for each new operating system, the latest is the Win2003 SP1 SDK, which is said to be released immediately, and has separated the UI APIs from the core library to improve the stability of the system. There are some C-language header files (. h files) in the SDK, which describe what Win32 API functions are in the core DLL files, and when writing the program, put these. h files into your program, and you can use these Win32 API. As to how the program is linked, beyond the scope of this article-also beyond the scope of my knowledge: D
At this point, if you are a C-language expert, you can already use the Windows SDK to tune Windows! Today, however, we are talking about the C # language calling the Win32 API. We now know that the API functions are placed in DLL dynamic link library files, but also know how C language calls them, then C # language How to do? C # language is a. h file that cannot be used in C. The C # language also uses DLL dynamic-link libraries, but these DLLs are. NET version, with "self-descriptive", that is, what functions in their belly have been written in their own metadata, no need to attach an. h file to explain. Now, we have found the key point of the problem: how to use it. The C # language on the Win32 platform to invoke DLL files on the. NET platform. The answer is simple: Use the DllImport feature
two. Small trial sledgehammer
Below, let's write a small program, try to use the C # language and DllImport features to invoke the Win32 API.
usingSystem;usingSystem.Runtime.InteropServices;classprogram{[DllImport ("User32.dll")]      Public Static extern intMessageBox (intHstringMstringCinttype); Static intMain () {MessageBox (0,"Hello Win32 API","the essence of water",4);         Console.ReadLine (); return 0; }}

Create a new C # console program, empty vs Auto-generated code, and copy the code above to compile and execute. Let's dissect this program:

1. To use the DllImport feature (which is also a class), it is necessary to use this sentence using System.Runtime.InteropServices;
, import "Run-time interactive services". Oh ~ ~ ~ is the interactive service at runtime not a "dynamic link"? Thanks microsoft!
2. Then we can create an instance of the DllImport class and bind the instance to the function we want to use. This kind of "attribute class" is very strange--do not use MyClass MC = new MyClass () When making class instances, but use [attribute Class (parameter list)]This form, the attribute class cannot exist independently, must be used to modify other targets (in this case, a function that is modified later), different attributes can be used to modify classes, functions, variables, etc., the attribute class instance is compiled without executable code, but is put into metadata for retrieval. In short, you remember the characteristics of the class is very strange, want to know more on MSDN, too lazy to check on the first so remember-do not understand inertia does not affect you learn to ride a bicycle. [DllImport ("User32.dll")] is that we are going to use the Win32 API function in User32.dll this file. Here's the question: How do I know which DLL file that so many API functions are in? This you can find on MSDN, the location is Root->win32 and COM development->development guides->windows api->windows api->windows API Reference->functions by Category。 Open this page, you will see a lot of API classification, the API is all here. Open a category, such as dialog Box, in the functions segment, you will see a lot of specific functions, which have the MessageBox function used above, click to enter. You will open a detailed explanation and specific usage of the MessageBox. Its name, return value, parameter type panoramic view, sweeping! And very practice English Oh ~ ~ ~ at the bottom of this page, you can see a small table with a "Minimum DLL Version user32.dll" That means the function is in user32.dll.
3. The next step is our function. There are so many points to calling the Win32 function in C #. First: The name should be exactly the same as the Win32 API. Second: The function must be declared as public static extern type, in addition to the corresponding DllImport class adornments. Third: Also the most perverted point, the function of the return value and parameter type to be exactly the same as the Win32 API! This is difficult to us this group of beginners--WIN32 data types are more quirky, such as what LPSTR, what hinstance are some shrimp? Give everyone a small reference, my blog has the "Windows data type exploration-inscrutable you are?" "Series of humble text, you can check. Also here, I took a table from MSDN, which is a table of 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 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 devoted to this meaning.
With these things, we can turn a WIN32 API function into a C # function. Also take the MessageBox function as an example (see the function table just given), its WIN32 prototype is as follows:

Int MessageBox(HWND hWnd, LPCTSTR Lptext, LPCTSTR lpcaption, UINT Utype);

Name of function: The MessageBox will remain intact.
return value: int will remain unchanged (both Win32 and C#,int are 32-bit integers)
parameter Table: H means handle, generally HANDLD is pointer type, WIN32 platform pointer type is 32 bits to store, so in C # exactly corresponds to an int integer. However, since it is a pointer, there is no positive or negative points, the 32-bit should be used to save the value-this way, with a uint (unsigned 32-bit integer) to correspond to the Win32 h type more reasonable. However, as a reminder, int is supported by both C # and. NET CLR, and UINT is supported only by C # and not by the. NET CLR, so this example honestly uses the int type. (Hungry ...) and insist on ... )
As for LPCTSTR is the abbreviation for long Pointer to Constant string, which is plainly--the string. So, using the string type in C # is right.
modifier: Requires a corresponding DllImport and public static extern

After the above toss, the Win32 MessageBox function is packaged into a function that C # can call:

[DllImport ("User32.dll")]
public static extern int MessageBox (int h, string m, string c, int type);

Good people do the bottom, I put four parameters of the usefulness of also say:
first one: Who is the parent window that pops up the MessageBox. Not in this case, so it is 0, which is the "null pointer".
a second: The contents of the MessageBox. In this example, "Hello Win32 API".
a third: The header of the MessageBox. This example is the name of my blog-the true meaning of water-please do not forget.
Fourth One: What is the button on the MessageBox, if it is 0, then only one ok,messagebox is too short, you will not see the "Essence of water" four words, so I changed to 4, so there are two buttons. These are available in the MSDN function usage. However, I would highly recommend you to read my other article my book the evolution of a WIN32 program
At this point, a wudu and ~~~sorry-_-! Perfectly formed's C # call to Win32 API's program is done. The principle is not difficult! Fresh students take to the HR enough! The real foundation is where you are using the MSDN, SDK,. NET Framework class Library vc/vc# proficiency level. Believe me,--msdn+sdk+vc/c# is definitely enough to get Windows Obey Orders: D
three. Is it really necessary?
Hey hey heh ... Look at my face, I'm laughing in the bad place! You're all fooled! Operating the bottom of Windows does not have to call the Win32 API drip ~ ~ ~ ~ ~! )
What I want to say is that the. NET Framework is a good encapsulation of the Win32 API, and most of the Win32 API functions are already encapsulated in the various classes of the. NET Framework class library. If the Win32 API function is a pearl scattered on the ground, then the. NET framework puts these pearls in various drawers by category--reminds me of my mom--I always find my book when it's all over the bed, and when she's done I'll never find it, depressed. Alas...... There is no way, we still carefully put the. NET Framework class library upside down, there will be a lot of surprises Oh!
Finally, end our article with an example!
Example is such a drop ~~~~~
That was a long time ago, I gave a company to write programs used to control user login, before logging in, the user can not move the mouse out of the login form, because to control the mouse, so I first think of the call Win32 API with the cursor-related functions to--so regardless of 3,721, Spent Dickens called the Win32 API in the Clipcursor () This function, the effect is good.
The results of the first two days of flipping the. NET Framework class library found that the clip attribute of the System.Windows.Forms.Cursor class was dedicated to this use! I almost didn't get my nose out of the air ... Please do your own to create a C # Windows program, paste the following core code into the main form of the double-click event, try. The purpose of this example is to tell you: 1. The knowledge of the class library directly determines the efficiency and quality of your programming--it is much faster and safer to use the components in a class library than we "build from the wheel". 2. Do not go directly to the Win32 API function-it 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, we must be very interested to know, the. NET framework has been packaged for us which Win32 Api,ok,msdn has an article specifically listed here. The article's name is "Microsoft Win32 to Microsoft. NET Framework API Map" Please read to your friends of interest.

C # and Win32 API calls

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.