Using getcursorpos as an example, it returns the position of the current mouse pointer on the screen (with a point structure ).
For definitions of getcursorpos and point, refer to msdn:
Http://msdn.microsoft.com/en-us/library/ms648390 (V = vs.85). aspx
Http://msdn.microsoft.com/en-us/library/dd162805 (V = vs.85). aspx
First, use a custom C # struct to call getcursorpos. Everything looks simple.
Define a memory continuous struct point, and use the out parameter in the platform call life, because getcursorpos requires a point pointer! In execution, first declare a point variable (which involves space allocation), then call getcursorpos, and finally output the structure, correct!
Static void main ()
{
Point P;
Getcursorpos (Out P );
Console. writeline (P );
}
[Structlayout (layoutkind. Sequential)]
Struct point
{
Public int X, Y;
Public override string tostring ()
{
Return string. Format ("({0}, {1})", x, y );
}
}
[Dllimport ("user32.dll")]
Static extern void getcursorpos (out point P );
Next let's take a look at using a point class (rather than a struct) to implement the above functions. First, the out parameter is not required in the life of the platform call, because the class is a reference type and itself is a pointer!
Next, it is important to use the outattribute attribute to indicate the point parameter, because the default value is inattribute (if there is no ref/out ).
Finally, it is the space allocation. The reference type needs to be allocated with new.
Once everything above is set, the call can be successful. Code:
Static void main ()
{
Point P = new point ();
Getcursorpos (P );
Console. writeline (P );
}
[Structlayout (layoutkind. Sequential)]
Class Point
{
Public int X, Y;
Public override string tostring ()
{
Return string. Format ("({0}, {1})", x, y );
}
}
[Dllimport ("user32.dll")]
Static extern void getcursorpos ([out] point P );
Note that the structlayout feature can also modify the class!