c# 用sendkeys类 实现ctrl+C遇到的问题
SunShine
当你把Ctrl+C注册成系统热键时,要用SendKeys.Send("^c")实现原有的复制功能,注意c是小写的,大写的在有些程序中无效
以下是我的学习过程
最近学弟作了个东西
复制网页上的东西,导入到数据库,当需要的时候,再导成文本文件,在手机里看。
当实现按二次ctrl+c时,把文本放到数据库时遇到了第一个问题:
调用系统的RegisterHotkey函数注册全局热键,会使原来的Ctrl+c的复制功能失效
于是想到第二个方法,用系统WindowFromPoint获取鼠标所在窗口的句柄,再用sendMessage函数向这个句柄发送WM_COPY命令实现复制命令,遇到了第二个问题,在文本文件中,功能好用,到IE浏览器就不行了。
于是想到了第三个方法,向IE发送ctrl+c的模拟键盘命令,使用C#的SendKeys.Send(string s);函数,这个用的SendKeys.Send("^C"),可是还是不行,在文本文件中,功能好用,到IE浏览器就不行了。
怪了,又尝试SendKeys.Send("asdfasdf"),在IE的文本框中好用,可是SendKeys.Send("^C")就不行,怒了尝试用SendKeys.Send("%{F4}"),也是好用的。于是在网上baidu了n久看到了一片文章,SendKeys.Send(string s)是不是区分大小写啊,于是尝试SendKeys.Send("^c"),功能实现。
以下是用到的API函数
//发送消息
[DllImport("User32.dll", EntryPoint = "SendMessage")]
private static extern int SendMessage(
int hWnd, // handle to destination window
int Msg, // message
int wParam, // first message parameter
int lParam // second message parameter
);
//获取鼠标所在的窗口句柄
[DllImport("user32.dll", SetLastError = true)]
private static extern IntPtr WindowFromPoint(int x, int y);
//获取鼠标的位置
[DllImport("user32.dll", SetLastError = true)]
private static extern void GetCursorPos(ref Point p);
//注册热键
[DllImport("user32.dll", SetLastError = true)]
public static extern bool RegisterHotKey(
IntPtr hWnd,
int id,
KeyModifiers fsModifiers,
Keys vk
);
//卸载热键
[DllImport("user32.dll", SetLastError = true)]
public static extern bool UnregisterHotKey(
IntPtr hWnd,
int id
);
[Flags()]
//按键修饰符
public enum KeyModifiers
{
None = 0,
Alt = 1,
Control = 2,
Shift = 4,
Windows = 8
}