本文介绍了剪贴板监视器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有问题。我正在尝试将ClipboardMonitor用于我的C#应用​​程序。目标是监视剪贴板中的每个更改。
开始监视时:

I have a problem. i am trying to use the ClipboardMonitor for my C# Application. The goal is to monitor every change in the clipboard.When starting to monitor:

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

But when putting a breakpoint at the method call ClipboardMonitor_OnClipboardChange and changing the Clipboard I never get to it.

推荐答案

问题是您正在处理错误的窗口消息。引用 AddClipboardFormatListener

The problem is that you're handling the wrong window message. Quoting the documentation for AddClipboardFormatListener:

代码为:

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;
    }
}

这篇关于剪贴板监视器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-22 09:42