A Windows API is an API function for a Windows operating system. In C #, calling a Windows API is actually a call of a hosted code to an unmanaged code.
The main format is:
using System.Runtime.InteropServices;
namespace TestWinAPI1
{
class Program
{
static void Main(string[] args)
{
Beep(100, 100);
}
[DllImport("kernel32", CharSet = CharSet.Ansi)]
public static extern bool Beep(int frequery, int duration);
}
}
Beep is the call of Win API, which is called using the [DllImport ("kernel32")] attribute.
The original definition of this function in MSDN is:
C++
BOOL WINAPI Beep(
__in DWORD dwFreq,
__in DWORD dwDuration
);
To call BeepAPI, we must:
1. Map DWORD to int in C #, and set the number and position of corresponding parameters correctly.
2. The called function name is the same as the function name in WinAPI.
In this way, we can use Win API to operate Windows in C.
The following resources are indispensable for using WindowsAPI:
MSDN: http://msdn.microsoft.com/en-us/library/ee663300 (VS.85). aspx
Recommended getting started Tutorial: http://www.docin.com/p-4510006.html
Difficulties in using WINAPI:
1. How does each data type in C ++ correspond to C?
There is no unique rule for using the Data Type in C # to correspond to the Data Type in C ++, but the memory usage should be consistent.
When a pointer exists in C ++, we can use ref to pass the pointer.
2. How can I operate a data structure defined in C ++?
We should also define the data structure consistent with the storage structure in C #.
The following operations use WinAPI to simulate mouse positioning and left-click standalone operations:
Code
namespace TestWinAPI1
{
public struct Point
{
int x;
int y;
}
class Program
{
static void Main(string[] args)
{
Point point = new Point();
bool getResult = GetCursorPos(ref point);
int setRight = SetCursorPos(27, 881);
MouseClick("left");
}
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern bool GetCursorPos(ref Point point);
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
public static extern IntPtr GetCursor();
[DllImport("user32")]