我有个问题.我正在尝试将ClipboardMonitor用于我的C#应用程序.目标是监控剪贴板中的每个更改.
开始监控时:
AddClipboardFormatListener(this.Handle);
当停止听众时:
RemoveClipboardFormatListener(this.Handle);
和覆盖方法:
const int WM_DRAWCLIPBOARD = 0x308;
const int WM_CHANGECBCHAIN = 0x030D;
protected override void WndProc(ref Message m)
{
switch (m.Msg)
{
case WM_DRAWCLIPBOARD:
IDataObject iData = Clipboard.GetDataObject();
if (iData.GetDataPresent(DataFormats.Text))
{
ClipboardMonitor_OnClipboardChange((string)iData.GetData(DataFormats.Text));
}
break;
default:
base.WndProc(ref m);
break;
}
}
当然还有DLL导入:
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool AddClipboardFormatListener(IntPtr hwnd);
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool RemoveClipboardFormatListener(IntPtr hwnd);
但是当在方法中调用一个断点时,调用ClipboardMonitor_OnClipboardChange并更改剪贴板,我从来没有得到它.
解决方法:
问题是你正在处理错误的窗口消息.引用AddClipboardFormatListener
的文档:
When a window has been added to the clipboard format listener list, it is posted a
WM_CLIPBOARDUPDATE
message whenever the contents of the clipboard have changed.
有了这些知识,请将代码更改为:
const int WM_CLIPBOARDUPDATE = 0x031D;
protected override void WndProc(ref Message m)
{
switch (m.Msg)
{
case WM_CLIPBOARDUPDATE:
IDataObject iData = Clipboard.GetDataObject();
if (iData.GetDataPresent(DataFormats.Text))
{
string data = (string)iData.GetData(DataFormats.Text);
}
break;
default:
base.WndProc(ref m);
break;
}
}