在研究如何模仿 搜狗输入法截图功能时的发现!可以用键盘或者编程的方式控制当前,鼠标光标的位置!废话不多说,主要要用到一个WinApi函数!
/// 设置鼠标光标在整个屏幕的位置
SetCursorPos(
int X, // 鼠标的X坐标
int Y // 鼠标的Y坐标
)
注:X,Y坐标是指相对于 整个屏幕的坐标,而不是当前应用程序的坐标!
///获取当前鼠标光标的在整个屏幕上的位置
GetCursorPos(
out point p // 以一个结构体的方式,放回当前的鼠标光标的位置!
)
注:这个api函数,在.net类库中可以找到,相对应的托管代码!那就是Cursor这个类中的pos属性!有兴趣的朋友可以翻看MSDN关于这个类的相关信息!
下面是demo(支持非窗口焦点的情况下)
、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、
private enum MouseAction : int
{
MOUSEEVENTF_MOVE = 0x0001, //移动鼠标
MOUSEEVENTF_LEFTDOWN = 0x0002,// 模拟鼠标左键按下
MOUSEEVENTF_LEFTUP = 0x0004, //模拟鼠标左键抬起
MOUSEEVENTF_RIGHTDOWN = 0x0008,// 模拟鼠标右键按下
MOUSEEVENTF_RIGHTUP = 0x0010, //模拟鼠标右键抬起
MOUSEEVENTF_MIDDLEDOWN = 0x0020, //模拟鼠标中键按下
MOUSEEVENTF_MIDDLEUP = 0x0040, //模拟鼠标中键抬起
MOUSEEVENTF_ABSOLUTE = 0x8000 //标示是否采用绝对坐标
}
[DllImport("User32")]
public extern static void SetCursorPos(int x, int y);
[DllImportAttribute("user32.dll", EntryPoint = "RegisterHotKey")]
private static extern bool registerHotKey
(
IntPtr hWnd, //接受热键的窗口句柄(句柄:窗体的系统代号)
int id, //热键编号
int fsModifiers, //是否为组合键 例如ctrl shift 等等
int vk //一般按键 a,c 等等
);
[DllImportAttribute("user32.dll", EntryPoint = "UnregisterHotKey")]
private static extern bool unregisterHotKey
(
IntPtr hWnd, //接受热键的窗口句柄(句柄:窗体的系统代号)
int id //热键编号上面注册热键的编号
);
[System.Runtime.InteropServices.DllImport("user32")]
private static extern int mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo);
private void frmMain_Load(object sender, EventArgs e)
{
registerHotKey(this.Handle, 10001, 0, (int)Keys.Left);
registerHotKey(this.Handle, 10002, 0, (int)Keys.Right);
registerHotKey(this.Handle, 10003, 0, (int)Keys.Up);
registerHotKey(this.Handle, 10004, 0, (int)Keys.Down);
registerHotKey(this.Handle, 10005, 0, (int)Keys.Enter);
}
private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
{
unregisterHotKey(this.Handle, 10001);
unregisterHotKey(this.Handle, 10002);
unregisterHotKey(this.Handle, 10003);
unregisterHotKey(this.Handle, 10004);
unregisterHotKey(this.Handle, 10005);
} private void addInfoToList(String s)
{
//this.listBox1.Items.Add(s);
}
protected override void WndProc(ref Message m)
{
const int WM_HOTKEY = 0x0312;
switch (m.Msg)
{
case WM_HOTKEY:
Point nowPoint = Cursor.Position;
switch (m.WParam.ToInt32())
{
case 10001:
SetCursorPos(nowPoint.X - 10, nowPoint.Y);
base.WndProc(ref m);
break;
case 10002:
SetCursorPos(nowPoint.X + 10, nowPoint.Y);//设置当前鼠标的位置
base.WndProc(ref m);
break;
case 10003:
SetCursorPos(nowPoint.X, nowPoint.Y - 10);
base.WndProc(ref m);
break;
case 10004:
SetCursorPos(nowPoint.X, nowPoint.Y + 10);
base.WndProc(ref m);
break;
case 10005:
mouse_event((int)(MouseAction.MOUSEEVENTF_LEFTDOWN | MouseAction.MOUSEEVENTF_LEFTUP),
0,
0,
0,
0);
//mouse_event((int)(MouseAction.MOUSEEVENTF_LEFTDOWN | MouseAction.MOUSEEVENTF_LEFTUP),
// 0,
// 0,
// 0,
// 0);
//base.WndProc(ref m);
break;
}
break;
default:
base.WndProc(ref m);
break;
}
}