天天看点

如何使用C#操作WinAPI

windows api是对windows操作系统的api函数,在c#中调用windows api的实质是托管代码对非托管代码的调用。

主要使用的格式就是:

如何使用C#操作WinAPI

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);

如何使用C#操作WinAPI

其中的beep就是win api的调用,使用[dllimport("kernel32")]属性进行调用。

这个函数在msdn中的原本定义是:

c++

bool winapi beep(

__in dword dwfreq,

__in dword dwduration

);

我们想要调用beepapi,就必须:

1.将dword对应为c#中的int,相应的参数个数和位置设置正确

2.调用的函数名和winapi中的函数名一致

这样,我们在c#中就可以使用win api对windows进行操作。

这里几个资源是使用windowsapi不可或缺的:

使用winapi的难点:

1.c++中的各个数据类型如何对应到c#中?

使用c#中的那个数据类型对应那个c++的数据类型没有唯一的规定,但是应该站在内存使用的角度,选择内存占用大小一致。

当c++中存在指针的时候,我们可以使用ref来传递指针

2.如果c++中定义了数据结构如何操作?

我们也应该在c#中定义与之存储结构一致的数据结构

以下是用winapi 模拟鼠标定位和单机左键的操作:

如何使用C#操作WinAPI
如何使用C#操作WinAPI

public struct point

int x;

int y;

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")]

public static extern int setcursorpos(int x, int y);

[dllimport("user32.dll")]

static extern void mouse_event(uint dwflags, uint dx, uint dy, uint dwdata, int dwextrainfo);

[flags]

public enum mouseeventflags:uint

leftdown = 0x00000002,

leftup = 0x00000004,

middledown = 0x00000020,

middleup = 0x00000040,

move = 0x00000001,

absolute = 0x00008000,

rightdown = 0x00000008,

rightup = 0x00000010

/// <summary>

/// checks for the currently active window then simulates a mouseclick

/// </summary>

/// <param name="button">which button to press (left middle up)</param>

/// <param name="windowname">the window to send to</param>

public static void mouseclick(string button, string windowname)

if (windowactive(windowname))

mouseclick(button);

/// simulates a mouse click see http://pinvoke.net/default.aspx/user32/mouse_event.html?diff=y

public static void mouseclick(string button)

switch (button)

case "left":

mouse_event((uint)mouseeventflags.leftdown|(uint)mouseeventflags.leftup, 0, 0, 0, 0);

break;

case "right":

mouse_event((uint)mouseeventflags.rightdown, 0, 0, 0, 0);

mouse_event((uint)mouseeventflags.rightup, 0, 0, 0, 0);

case "middle":

mouse_event((uint)mouseeventflags.middledown, 0, 0, 0, 0);

mouse_event((uint)mouseeventflags.middleup, 0, 0, 0, 0);

如何使用C#操作WinAPI

简要描述:

使用了mouse_event,getcursorpos,setcursorpos三个api

代表了单击左键的动作

int setright = setcursorpos(27, 881); 中的27,881是屏幕上的绝对位置

ps:使用api可以做一些游戏的小外挂,比如模拟鼠标,键盘的操作...嘿嘿