[转载]C#模拟键盘鼠标事件-SendKeys

C#模拟键盘鼠标事件-SendKeys

8596人阅读评论(1)收藏举报
1.模拟键盘事件
System.Windows.Forms.SendKeys
以下是   SendKeys   的一些特殊键代码表。  
  键   代码    
  BACKSPACE   {BACKSPACE}、{BS}   或   {BKSP}    
  BREAK   {BREAK}    
  CAPS   LOCK   {CAPSLOCK}    
  DEL   或   DELETE   {DELETE}   或   {DEL}    
  DOWN   ARROW(下箭头键)   {DOWN}    
  END   {END}    
  ENTER   {ENTER}   或   ~    
  ESC   {ESC}    
  HELP   {HELP}    
  HOME   {HOME}    
  INS   或   INSERT   {INSERT}   或   {INS}    
  LEFT   ARROW(左箭头键)   {LEFT}    
  NUM   LOCK   {NUMLOCK}    
  PAGE   DOWN   {PGDN}    
  PAGE   UP   {PGUP}    
  PRINT   SCREEN   {PRTSC}(保留,以备将来使用)    
  RIGHT   ARROW(右箭头键)   {RIGHT}    
  SCROLL   LOCK   {SCROLLLOCK}    
  TAB   {TAB}    
  UP   ARROW(上箭头键)   {UP}    
  F1   {F1}    
  F2   {F2}    
  F3   {F3}    
  F4   {F4}    
  F5   {F5}    
  F6   {F6}    
  F7   {F7}    
  F8   {F8}    
  F9   {F9}    
  F10   {F10}    
  F11   {F11}    
  F12   {F12}    
  F13   {F13}    
  F14   {F14}    
  F15   {F15}    
  F16   {F16}    
  数字键盘
加号   {ADD}    
  数字键盘减号   {SUBTRACT}    
  数字键盘乘号   {MULTIPLY}    
  数字
键盘除号   {DIVIDE}    
   
  若要指定与   SHIFT、CTRL   和   ALT   键的任意组合一起使用的键,请在这些键代码之前加上以下一个或多个代码:  
   
  键   代码    
  SHIFT   +     (SHIFT="+")
  CTRL   ^     (CTRL="^") 如果输入
  ALT   %    
private void button1_Click(object sender, System.EventArgs e)
        {//英文输入
this.richTextBox1.Focus();                                            
for(int i=65;i<91;i++)
            {
char Letter=(char)i;
                SendKeys.Send(Letter.ToString());
                System.Threading.Thread.Sleep(100);        
                SendKeys.Flush();
            }        
for(int i=97;i<123;i++)
            {
char Letter=(char)i;
                SendKeys.Send(Letter.ToString());
                System.Threading.Thread.Sleep(100);
                SendKeys.Flush();
            }        
        }
 
private void button3_Click(object sender, System.EventArgs e)
        {//数字输入
this.richTextBox1.Focus();                                            
for(int i=0;i<10;i++)
            {                
                SendKeys.Send(i.ToString());
                System.Threading.Thread.Sleep(100);        
                SendKeys.Flush();
            }                
        }
 
private void button4_Click(object sender, System.EventArgs e)
        {//Backspace
this.richTextBox1.Focus();
            SendKeys.Send("{Backspace}");        
        }
 
private void button5_Click(object sender, System.EventArgs e)
        {//Home
this.richTextBox1.Focus();
            SendKeys.Send("{Home}");                
        }
 
private void button6_Click(object sender, System.EventArgs e)
        {//End
this.richTextBox1.Focus();
            SendKeys.Send("{End}");        
        }
 
private void button7_Click(object sender, System.EventArgs e)
        {//Enter
this.richTextBox1.Focus();
            SendKeys.Send("{Enter}");        
        }
 
private void button8_Click(object sender, System.EventArgs e)
        {//Delete
this.richTextBox1.Focus();
            SendKeys.Send("{Delete}");        
        }
 
private void button2_Click(object sender, System.EventArgs e)
        {//Shift+Home
this.richTextBox1.Focus();
            SendKeys.Send("+{Home}");                
        }
 
private void button9_Click(object sender, System.EventArgs e)
        {//Shift+End
this.richTextBox1.Focus();
            SendKeys.Send("+{End}");                

}

看下方法的说明


public class SendKeys : System.Object
    System.Windows.Forms 的成员
 
摘要:
 提供将键击发送到应用程序的方法。  

public static void Send ( System.String keys )
    System.Windows.Forms.SendKeys 的成员
 
摘要:
 向活动应用程序发送击键。  

public static void Sleep ( System.TimeSpan timeout )
    System.Threading.Thread 的成员
 
摘要:

将当前线程阻塞指定的时间。



public static void Flush (  )
    System.Windows.Forms.SendKeys 的成员
 
2.模拟鼠标
有时,我们需在我们的程序中模拟鼠标的移动、点击等动作。——比如,一个再现用户操作的宏,或者一个演示操作方法的Demo程序。那么,我们在.Net中如何实现呢?

.Net并没有提供改变鼠标指针位置、模拟点击操作的函数;但是Windows API提供了。其中一个是:
[DllImport("user32.dll")]
static extern bool SetCursorPos(int X, int Y);

该函数可以改变鼠标指针的位置。其中X,Y是相对于屏幕左上角的绝对位置。
另一个函数是:

[DllImport("user32.dll")]
static extern void mouse_event(MouseEventFlag flags, int dx, int dy, uint data, UIntPtr extraInfo);

这个函数不仅可以设置鼠标指针绝对的位置,而且可以以相对坐标来设置。另外,该函数还可以模拟鼠标左右键点击、鼠标滚轮操作等。其中的MouseEventFlag是一个基于uint类型的枚举,定义如下:

[Flags]
enum MouseEventFlag : uint
{
Move
= 0x0001,
LeftDown
= 0x0002,
LeftUp
= 0x0004,
RightDown
= 0x0008,
RightUp
= 0x0010,
MiddleDown
= 0x0020,
MiddleUp
= 0x0040,
XDown
= 0x0080,
XUp
= 0x0100,
Wheel
= 0x0800,
VirtualDesk
= 0x4000,
Absolute
= 0x8000
}

关于这两个函数的详细说明,可以查看MSDN Library或者Windows的Platform SDK文档。
下面的演示程序(完整版源代码,VS.Net 2005/C#)演示了使用上面的函数,控制鼠标移动到任务栏并点击“开始”按钮的方法。
(该程序使用了FindWindowEx等API函数来查找任务栏及开始菜单)

点这里下载

posted on 2007-08-07 22:01 Thunderdanky 阅读(185) 评论(3)  编辑  收藏 所属分类: .NET技术文章

FeedBack:
# re: C#模拟键盘鼠标事件
2007-08-07 22:01 | Thunderdanky
看一个参考MSDN上的
如何:在代码中模拟鼠标和键盘事件

Windows 窗体提供以编程方式模拟鼠标和键盘输入的几个选项。本主题提供这些选项的概述。

模拟鼠标输入
模拟鼠标事件的最佳方法是调用引发要模拟的鼠标事件的 OnEventName 方法。此选项通常只在自定义控件和窗体中是可能的,因为引发事件的方法受保护,而且不能从控件或窗体外部访问。例如,下面的步骤阐释如何用代码模拟单击鼠标右键的事件。

以编程方式单击鼠标右键
创建一个 Button 属性设置为 System.Windows.Forms.MouseButtons.Right 值的 MouseEventArgs。

将此 MouseEventArgs 用作参数调用 OnMouseClick 方法。

有关自定义控件的更多信息,请参见 设计时开发 Windows 窗体控件。

还有其他模拟鼠标输入的方法。例如,可以通过编程方式设置一个表示通常通过鼠标输入设置的状态的控件属性(如 CheckBox 控件的 Checked 属性),或者您可以直接调用附加到要模拟的事件的委托。

模拟键盘输入
虽然您可以通过使用上面讨论的鼠标输入策略来模拟键盘输入,但 Windows 窗体还提供了用于将键击发送到活动应用程序的 SendKeys 类。

警告
如果您的应用程序打算用于可以使用各种键盘的国际使用,则使用 System.Windows.Forms.SendKeys.Send(System.String) 可能产生不可预知的结果,因而应当避免。


注意
SendKeys 类已针对 .NET Framework 3.0 进行了更新,能够用于在 Windows Vista 上运行的应用程序中。Windows Vista 增强的安全性(称为用户账户控件或 UAC)使以前的实现无法按预期方式工作。

SendKeys 类容易出现计时问题,有些开发人员必须解决这个问题。更新的实现仍然容易发生计时问题,但速度略有提高,并且可能要求更改解决方法。SendKeys 类首先会尝试使用以前的实现,失败后再使用新的实现。因此,SendKeys 类的行为可能因操作系统的不同而有所差异。此外,当 SendKeys 类使用新的实现时,SendWait 方法在消息被发送到另一进程时不会等待消息的处理。

如果您的应用程序依赖于不受操作系统影响的一致性行为,则可通过向 app.config 文件添加以下应用程序设置,强制 SendKeys 类使用新的实现。

<appSettings>

<add key="SendKeys" value="SendInput"/>

</appSettings>

要强制 SendKeys 类使用以前的实现,请改用值 "JournalHook"。


向同一应用程序发送键击
调用 SendKeys 类的 Send 或 SendWait 方法。应用程序的活动控件将接收指定的键击。下面的代码示例使用 Send 在用户双击窗体的图面时模拟按 Enter 键。此示例假定一个 Form,该窗体具有单个 Tab 键索引为 0 的 Button 控件。

Visual Basic 复制代码
' Send a key to the button when the user double-clicks anywhere
' on the form.
Private Sub Form1_DoubleClick(ByVal sender As Object, _
ByVal e As EventArgs) Handles Me.DoubleClick

' Send the enter key to the button, which raises the click
' event for the button. This works because the tab stop of
' the button is 0.
SendKeys.Send("{ENTER}")
End Sub

C# 复制代码
// Send a key to the button when the user double-clicks anywhere
// on the form.
private void Form1_DoubleClick(object sender, EventArgs e)
{
// Send the enter key to the button, which raises the click
// event for the button. This works because the tab stop of
// the button is 0.
SendKeys.Send("{ENTER}");
}

C++ 复制代码
// Send a key to the button when the user double-clicks anywhere
// on the form.
private:
void Form1_DoubleClick(Object^ sender, EventArgs^ e)
{
// Send the enter key to the button, which triggers the click
// event for the button. This works because the tab stop of
// the button is 0.
SendKeys::Send("{ENTER}");
}

向另一个应用程序发送键击
激活将接收键击的应用程序窗口,然后调用 Send 或 SendWait 方法。由于没有激活另一个应用程序的托管方法,因此必须使用本机 Windows 方法强制将焦点放在其他应用程序上。下面的代码示例使用平台调用来调用 FindWindow 和 SetForegroundWindow 方法,以激活计算器应用程序窗口,然后调用 SendWait 向计算器应用程序发出一系列计算。

Visual Basic 复制代码
' Get a handle to an application window.
Declare Auto Function FindWindow Lib "USER32.DLL" ( _
ByVal lpClassName As String, _
ByVal lpWindowName As String) As IntPtr

' Activate an application window.
Declare Auto Function SetForegroundWindow Lib "USER32.DLL" _
(ByVal hWnd As IntPtr) As Boolean

' Send a series of key presses to the Calculator application.
Private Sub button1_Click(ByVal sender As Object, _
ByVal e As EventArgs) Handles button1.Click

' Get a handle to the Calculator application. The window class
' and window name were obtained using the Spy++ tool.
Dim calculatorHandle As IntPtr = FindWindow("SciCalc", "Calculator")

' Verify that Calculator is a running process.
If calculatorHandle = IntPtr.Zero Then
MsgBox("Calculator is not running.")
Return
End If

' Make Calculator the foreground application and send it
' a set of calculations.
SetForegroundWindow(calculatorHandle)
SendKeys.SendWait("111")
SendKeys.SendWait("*")
SendKeys.SendWait("11")
SendKeys.SendWait("=")
End Sub

C# 复制代码
// Get a handle to an application window.
[DllImport("USER32.DLL")]
public static extern IntPtr FindWindow(string lpClassName,
string lpWindowName);

// Activate an application window.
[DllImport("USER32.DLL")]
public static extern bool SetForegroundWindow(IntPtr hWnd);

// Send a series of key presses to the Calculator application.
private void button1_Click(object sender, EventArgs e)
{
// Get a handle to the Calculator application. The window class
// and window name were obtained using the Spy++ tool.
IntPtr calculatorHandle = FindWindow("SciCalc", "Calculator");

// Verify that Calculator is a running process.
if (calculatorHandle == IntPtr.Zero)
{
MessageBox.Show("Calculator is not running.");
return;
}

// Make Calculator the foreground application and send it
// a set of calculations.
SetForegroundWindow(calculatorHandle);
SendKeys.SendWait("111");
SendKeys.SendWait("*");
SendKeys.SendWait("11");
SendKeys.SendWait("=");
}

C++ 复制代码
// Get a handle to an application window.
public:
[DllImport("USER32.DLL")]
static IntPtr FindWindow(String^ lpClassName, String^ lpWindowName);
public:
// Activate an application window.
[DllImport("USER32.DLL")]
static bool SetForegroundWindow(IntPtr hWnd);

// Send a series of key presses to the Calculator application.
private:
void button1_Click(Object^ sender, EventArgs^ e)
{
// Get a handle to the Calculator application. The window class
// and window name were obtained using the Spy++ tool.
IntPtr calculatorHandle = FindWindow("SciCalc", "Calculator");

// Verify that Calculator is a running process.
if (calculatorHandle == IntPtr::Zero)
{
MessageBox::Show("Calculator is not running.");
return;
}

// Make Calculator the foreground application and send it
// a set of calculations.
SetForegroundWindow(calculatorHandle);
SendKeys::SendWait("111");
SendKeys::SendWait("*");
SendKeys::SendWait("11");
SendKeys::SendWait("=");
}

示例
下面的代码示例是前面代码示例的完整应用。

Visual Basic 复制代码
Imports System
Imports System.Runtime.InteropServices
Imports System.Drawing
Imports System.Windows.Forms

Namespace SimulateKeyPress

Class Form1
Inherits Form
Private WithEvents button1 As New Button()

<STAThread()> _
Public Shared Sub Main()
Application.EnableVisualStyles()
Application.Run(New Form1())
End Sub

Public Sub New()
button1.Location = New Point(10, 10)
button1.TabIndex = 0
button1.Text = "Click to automate Calculator"
button1.AutoSize = True
Me.Controls.Add(button1)
End Sub

' Get a handle to an application window.
Declare Auto Function FindWindow Lib "USER32.DLL" ( _
ByVal lpClassName As String, _
ByVal lpWindowName As String) As IntPtr

' Activate an application window.
Declare Auto Function SetForegroundWindow Lib "USER32.DLL" _
(ByVal hWnd As IntPtr) As Boolean

' Send a series of key presses to the Calculator application.
Private Sub button1_Click(ByVal sender As Object, _
ByVal e As EventArgs) Handles button1.Click

' Get a handle to the Calculator application. The window class
' and window name were obtained using the Spy++ tool.
Dim calculatorHandle As IntPtr = FindWindow("SciCalc", "Calculator")

' Verify that Calculator is a running process.
If calculatorHandle = IntPtr.Zero Then
MsgBox("Calculator is not running.")
Return
End If

' Make Calculator the foreground application and send it
' a set of calculations.
SetForegroundWindow(calculatorHandle)
SendKeys.SendWait("111")
SendKeys.SendWait("*")
SendKeys.SendWait("11")
SendKeys.SendWait("=")
End Sub

' Send a key to the button when the user double-clicks anywhere
' on the form.
Private Sub Form1_DoubleClick(ByVal sender As Object, _
ByVal e As EventArgs) Handles Me.DoubleClick

' Send the enter key to the button, which raises the click
' event for the button. This works because the tab stop of
' the button is 0.
SendKeys.Send("{ENTER}")
End Sub

End Class
End Namespace

C# 复制代码
using System;
using System.Runtime.InteropServices;
using System.Drawing;
using System.Windows.Forms;

namespace SimulateKeyPress
{
class Form1 : Form
{
private Button button1 = new Button();

[STAThread]
public static void Main()
{
Application.EnableVisualStyles();
Application.Run(new Form1());
}

public Form1()
{
button1.Location = new Point(10, 10);
button1.TabIndex = 0;
button1.Text = "Click to automate Calculator";
button1.AutoSize = true;
button1.Click += new EventHandler(button1_Click);

this.DoubleClick += new EventHandler(Form1_DoubleClick);
this.Controls.Add(button1);
}

// Get a handle to an application window.
[DllImport("USER32.DLL")]
public static extern IntPtr FindWindow(string lpClassName,
string lpWindowName);

// Activate an application window.
[DllImport("USER32.DLL")]
public static extern bool SetForegroundWindow(IntPtr hWnd);

// Send a series of key presses to the Calculator application.
private void button1_Click(object sender, EventArgs e)
{
// Get a handle to the Calculator application. The window class
// and window name were obtained using the Spy++ tool.
IntPtr calculatorHandle = FindWindow("SciCalc", "Calculator");

// Verify that Calculator is a running process.
if (calculatorHandle == IntPtr.Zero)
{
MessageBox.Show("Calculator is not running.");
return;
}

// Make Calculator the foreground application and send it
// a set of calculations.
SetForegroundWindow(calculatorHandle);
SendKeys.SendWait("111");
SendKeys.SendWait("*");
SendKeys.SendWait("11");
SendKeys.SendWait("=");
}

// Send a key to the button when the user double-clicks anywhere
// on the form.
private void Form1_DoubleClick(object sender, EventArgs e)
{
// Send the enter key to the button, which raises the click
// event for the button. This works because the tab stop of
// the button is 0.
SendKeys.Send("{ENTER}");
}
}
}

C++ 复制代码
#using <System.Drawing.dll>
#using <System.Windows.Forms.dll>
#using <System.dll>

using namespace System;
using namespace System::Runtime::InteropServices;
using namespace System::Drawing;
using namespace System::Windows::Forms;

namespace SimulateKeyPress
{

public ref class Form1 : public Form
{
public:
Form1()
{
Button^ button1 = gcnew Button();
button1->Location = Point(10, 10);
button1->TabIndex = 0;
button1->Text = "Click to automate Calculator";
button1->AutoSize = true;
button1->Click += gcnew EventHandler(this, &Form1::button1_Click);

this->DoubleClick += gcnew EventHandler(this,
&Form1::Form1_DoubleClick);
this->Controls->Add(button1);
}

// Get a handle to an application window.
public:
[DllImport("USER32.DLL")]
static IntPtr FindWindow(String^ lpClassName, String^ lpWindowName);
public:
// Activate an application window.
[DllImport("USER32.DLL")]
static bool SetForegroundWindow(IntPtr hWnd);

// Send a series of key presses to the Calculator application.
private:
void button1_Click(Object^ sender, EventArgs^ e)
{
// Get a handle to the Calculator application. The window class
// and window name were obtained using the Spy++ tool.
IntPtr calculatorHandle = FindWindow("SciCalc", "Calculator");

// Verify that Calculator is a running process.
if (calculatorHandle == IntPtr::Zero)
{
MessageBox::Show("Calculator is not running.");
return;
}

// Make Calculator the foreground application and send it
// a set of calculations.
SetForegroundWindow(calculatorHandle);
SendKeys::SendWait("111");
SendKeys::SendWait("*");
SendKeys::SendWait("11");
SendKeys::SendWait("=");
}

// Send a key to the button when the user double-clicks anywhere
// on the form.
private:
void Form1_DoubleClick(Object^ sender, EventArgs^ e)
{
// Send the enter key to the button, which triggers the click
// event for the button. This works because the tab stop of
// the button is 0.
SendKeys::Send("{ENTER}");
}
};
}

[STAThread]
int main()
{
Application::EnableVisualStyles();
Application::Run(gcnew SimulateKeyPress::Form1());
}


C#模拟键盘鼠标事件

一个简单的模拟键盘鼠标操作的类

一个简单的模拟键盘鼠标操作的类,扩充 VirtualKeys 枚举就可以了,或者直接写!

using System;
using System.Runtime.InteropServices;
using System.Text;
class Keyboard
{
const uint KEYEVENTF_EXTENDEDKEY = 0x1;
const uint KEYEVENTF_KEYUP = 0x2;
[DllImport("user32.dll")]
static extern short GetKeyState(int nVirtKey);
[DllImport("user32.dll")]
static extern void keybd_event(
byte bVk,
byte bScan,
uint dwFlags,
uint dwExtraInfo
);

public enum VirtualKeys: byte
{
VK_NUMLOCK = 0x90, //数字锁定键
VK_SCROLL = 0x91, //滚动锁定
VK_CAPITAL = 0x14, //大小写锁定
VK_A = 62
}


public static bool GetState(VirtualKeys Key)
{
return (GetKeyState((int)Key)==1);
}
public static void SetState(VirtualKeys Key, bool State)
{
if(State!=GetState(Key))
{
keybd_event(
(byte)Key,
0x45,
KEYEVENTF_EXTENDEDKEY | 0,
0
);
keybd_event(
(byte)Key,
0x45,
KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP,
0
);
}
}
}

示例:
模拟操作
Keyboard.SetState(
VirtualKeys.VK_CAPITAL,
!Keyboard.GetState(VirtualKeys.VK_CAPITAL)
);
得到键盘状态
Keyboard.GetState(VirtualKeys.VK_CAPITAL)

* 十进制值 标识符 IBM兼容键盘 

--------------------------------------------------------------------------------

1    VK_LBUTTON   鼠标左键
2    VK_RBUTTON   鼠标右键
3    VK_CANCEL   Ctrl+Break(通常不需要处理)
4    VK_MBUTTON   鼠标中键
8    VK_BACK    Backspace
9    VK_TAB     Tab
12   VK_CLEAR    Num Lock关闭时的数字键盘5
13   VK_RETURN   Enter(或者另一个)
16   VK_SHIFT    Shift(或者另一个)
17   VK_CONTROL   Ctrl(或者另一个)
18   VK_MENU    Alt(或者另一个)
19   VK_PAUSE    Pause
20   VK_CAPITAL   Caps Lock
27   VK_ESCAPE   Esc
32   VK_SPACE    Spacebar
33   VK_PRIOR    Page Up
34   VK_NEXT    Page Down
35   VK_END     End
36   VK_HOME    Home
37    VK_LEFT    左箭头
38   VK_UP     上箭头
39   VK_RIGHT   右箭头
40   VK_DOWN    下箭头
41   VK_SELECT   可选
42   VK_PRINT   可选
43   VK_EXECUTE  可选
44   VK_SNAPSHOT  Print Screen
45   VK_INSERT   Insert
46   VK_DELETE  Delete
47   VK_HELP   可选
48~57  无      主键盘上的0~9
65~90  无      A~Z
96~105  VK_NUMPAD0~VK_NUMPAD9   Num Lock打开时数字键盘上的0~9
106   VK_NULTIPLY         数字键盘上的*
107   VK_ADD           数字键盘上的+
108   VK_SEPARATOR        可选
109   VK_SUBTRACT         数字键盘上的-
110   VK_DECIMAL         数字键盘上的.
111   VK_DIVIDE          数字键盘上的/
112~135 VK_F1~VK_F24        功能键F1~F24
144   VK_NUMLOCK         Num Lock
145   VK_SCROLL          Scroll Lock

*/


突然发现在c#里面原来还有一个 System.Windows.Forms.SendKeys

不过这个只能模拟键盘


真正能模拟鼠标操作的代码在这里!找的我好辛苦啊!

函数声明:
private readonly int MOUSEEVENTF_LEFTDOWN = 0x2;
private readonly int MOUSEEVENTF_LEFTUP = 0x4;
[DllImport("user32")]
public static extern void mouse_event(int dwFlags, int dx, int dy, int dwData, int dwExtraInfo);

调用方法:
mouse_event(MOUSEEVENTF_LEFTDOWN, X * 65536 / 1024, Y * 65536 / 768, 0, 0);
mouse_event(MOUSEEVENTF_LEFTUP, X * 65536 / 1024, Y * 65536 / 768, 0, 0);
其中X,Y分别是你要点击的点的横坐标和纵坐标
posted @ 2012-01-12 12:23  火腿骑士  阅读(1035)  评论(0编辑  收藏  举报