c# 调用api实现模拟键盘输入举例(向QQ对话框发送字符串)

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

//调用API模拟键盘事件

usingSystem;

usingSystem.Collections.Generic;

ponentModel;

usingSystem.Data;

usingSystem.Drawing;

usingSystem.Linq;

usingSystem.Text;

usingSystem.Windows.Forms;

usingSystem.Diagnostics;

usingMicrosoft.Win32;

usingSystem.Runtime.InteropServices;//这个必须要引用

namespaceWindowsFormsApplication2{publicpartialclassForm1:Form{publicFor m1(){InitializeComponent();}//需要调用的API

//找到窗口(进程名称可空,窗口名称)

[System.Runtime.InteropServices.DllImport("user

32.dll",EntryPoint ="FindWindow")]

publicstaticexternIntPtrFindWindow(stringlpClassName,stringlpWindowName);

//把窗口放到最前面

[DllImport("USER

32.DLL")]

publicstaticexternboolSetForegroundWindow(IntPtrhWnd);//模拟键盘事件

[DllImport("User

32.dll")]

publicstaticexternvoidkeybd_event(BytebVk,BytebScan,Int32dwFlags,Int32dwEx traInfo);

//释放按键的常量

privateconstintKEYEVENTF_KEYUP = 2;

//发送消息

[DllImport("user

32.dll")]

privatestaticexternintSendMessage(IntPtrhWnd,intMsg,intwParam,intlParam);

[DllImport("user

32.dll")]//获取窗口大小

[return:

MarshalAs(UnmanagedType.Bool)]

staticexternboolGetWindowRect(IntPtrhWnd,refRECTlpRect);[StructLayout(Layo utKind.Sequential)]//获取窗口坐标

publicstructRECT{publicintLeft;//最左坐标

publicintTop;//最上坐标

publicintRight;//最右坐标

publicintBottom;//最下坐标}////显示窗口

//[DllImport("user

32.dll")]

//privatestaticexternboolShowWindow(IntPtrhWnd,intnCmdShow);#regionSend Message参数

privateconstintWM_KEYDOWN = 0X100;

privateconstintWM_KEYUP = 0X101;

privateconstintWM_SYSCHAR = 0X106;

privateconstintWM_SYSKEYUP = 0X105;

privateconstintWM_SYSKEYDOWN = 0X104;

privateconstintWM_CHAR = 0X102;

#endregion

//鼠标事件

privatereadonlyintMOUSEEVENTF_LEFTDOWN = 0x2;

privatereadonlyintMOUSEEVENTF_LEFTUP = 0x4;

[DllImport("user32")]

publicstaticexternvoidmouse_event(intdwFlags,intdx,intdy,intdwData,intdwExtr aInfo);

///

///发送一个字符串

///

///窗口句柄

///字符串

publicvoidInputStr(IntPtrk,stringInput){//不能发送汉字,只能发送键盘上有的内容也可以模拟shift+!等byte[] ch =

(ASCIIEncoding.ASCII.GetBytes(Input));for(inti = 0; i < ch.Length; i++){SendMessage(k, WM_CHAR, ch[i], 0);}}

privatevoidbutton1_Click_1(objectsender,EventArgse){

//例如你打开的是QQ对话框,对方的名字叫“宁波”

IntPtrk = FindWindow(null,"大学梦");

if(k.ToString() !="0"){SetForegroundWindow(k);//把找到的的对话框在最前面显示如果使用了这个方法

stringa ="hi~my name is zhanghongyuan";

InputStr(k, a);

SendMessage(k, WM_KEYDOWN, 0X0D, 0);//发

SendMessage(k, WM_KEYUP, 0X0D, 0);//送

SendMessage(k, WM_CHAR, 0X0D, 0);//回车}else{MessageBox.Show(this,"没有找到该程序");}}}

相关文档
最新文档