剪贴板更改通知?

发布于 2024-11-17 06:33:31 字数 103 浏览 3 评论 0原文

我知道如何将内容放入剪贴板以及如何从剪贴板检索内容。

但是,在这两个操作之间,另一个操作可能会更改剪贴板的内容。

有没有办法在任何应用程序修改剪贴板时收到通知?

I know how put content to and retrieve content from the clipboard.

However, between these two operations, it is possible for another operation to change the content of the clipboard.

Is there a way to be notified when any application modifies the clipboard?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

浪漫人生路 2024-11-24 06:33:31

您需要添加的唯一参考是 wpf 应用程序中的 Windows 窗体。我为我在互联网上找到的功能创建了一个包装器。

大多数示例所做的事情超出了我的需要,因此我决定创建自己的类。我喜欢隔离问题,因此此类仅在剪贴板更改时进行监听,并告诉您剪贴板上的数据类型。例如它是文本吗?一个图像?或者什么?

无论如何,这是我的包装:

using System;
using System.Windows.Forms;
using System.Threading;
using System.Runtime.InteropServices;

public static class ClipboardMonitor 
{
    public delegate void OnClipboardChangeEventHandler(ClipboardFormat format, object data);
    public static event OnClipboardChangeEventHandler OnClipboardChange;

    public static void Start()
    {
        ClipboardWatcher.Start();
        ClipboardWatcher.OnClipboardChange += (ClipboardFormat format, object data) =>
        {
            if (OnClipboardChange != null)
                OnClipboardChange(format, data);
        };
    }

    public static void Stop()
    {
        OnClipboardChange = null;
        ClipboardWatcher.Stop();
    }
    
    class ClipboardWatcher : Form
    {
        // static instance of this form
        private static ClipboardWatcher mInstance;

        // needed to dispose this form
        static IntPtr nextClipboardViewer;

        public delegate void OnClipboardChangeEventHandler(ClipboardFormat format, object data);
        public static event OnClipboardChangeEventHandler OnClipboardChange;

        // start listening
        public static void Start()
        {
            // we can only have one instance if this class
            if (mInstance != null)
                return;

            Thread t = new Thread(new ParameterizedThreadStart(x =>
            {
                Application.Run(new ClipboardWatcher());
            }));
            t.SetApartmentState(ApartmentState.STA); // give the [STAThread] attribute
            t.Start();
        }

        // stop listening (dispose form)
        public static void Stop()
        {
            mInstance.Invoke(new MethodInvoker(() =>
            {
                ChangeClipboardChain(mInstance.Handle, nextClipboardViewer);
            }));
            mInstance.Invoke(new MethodInvoker(mInstance.Close));

            mInstance.Dispose();

            mInstance = null;
        }

        // on load: (hide this window)
        protected override void SetVisibleCore(bool value)
        {
            CreateHandle();

            mInstance = this;

            nextClipboardViewer = SetClipboardViewer(mInstance.Handle);

            base.SetVisibleCore(false);
        }

        [DllImport("User32.dll", CharSet = CharSet.Auto)]
        public static extern IntPtr SetClipboardViewer(IntPtr hWndNewViewer);

        [DllImport("User32.dll", CharSet = CharSet.Auto)]
        public static extern bool ChangeClipboardChain(IntPtr hWndRemove, IntPtr hWndNewNext);

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern int SendMessage(IntPtr hwnd, int wMsg, IntPtr wParam, IntPtr lParam);

        // defined in winuser.h
        const int WM_DRAWCLIPBOARD = 0x308;
        const int WM_CHANGECBCHAIN = 0x030D;

        protected override void WndProc(ref Message m)
        {
            switch (m.Msg)
            {
                case WM_DRAWCLIPBOARD:
                    ClipChanged();
                    SendMessage(nextClipboardViewer, m.Msg, m.WParam, m.LParam);
                    break;

                case WM_CHANGECBCHAIN:
                    if (m.WParam == nextClipboardViewer)
                        nextClipboardViewer = m.LParam;
                    else
                        SendMessage(nextClipboardViewer, m.Msg, m.WParam, m.LParam);
                    break;

                default:
                    base.WndProc(ref m);
                    break;
            }
        }

        static readonly string[] formats = Enum.GetNames(typeof(ClipboardFormat));

        private void ClipChanged()
        {
            IDataObject iData = Clipboard.GetDataObject();

            ClipboardFormat? format = null;

            foreach (var f in formats)
            {
                if (iData.GetDataPresent(f))
                {
                    format = (ClipboardFormat)Enum.Parse(typeof(ClipboardFormat), f);
                    break;
                }
            }

            object data = iData.GetData(format.ToString());

            if (data == null || format == null)
                return;

            if (OnClipboardChange != null)
                OnClipboardChange((ClipboardFormat)format, data);
        }


    }
}

public enum ClipboardFormat : byte
{
    /// <summary>Specifies the standard ANSI text format. This static field is read-only.
    /// </summary>
    /// <filterpriority>1</filterpriority>
    Text,
    /// <summary>Specifies the standard Windows Unicode text format. This static field
    /// is read-only.</summary>
    /// <filterpriority>1</filterpriority>
    UnicodeText,
    /// <summary>Specifies the Windows device-independent bitmap (DIB) format. This static
    /// field is read-only.</summary>
    /// <filterpriority>1</filterpriority>
    Dib,
    /// <summary>Specifies a Windows bitmap format. This static field is read-only.</summary>
    /// <filterpriority>1</filterpriority>
    Bitmap,
    /// <summary>Specifies the Windows enhanced metafile format. This static field is
    /// read-only.</summary>
    /// <filterpriority>1</filterpriority>
    EnhancedMetafile,
    /// <summary>Specifies the Windows metafile format, which Windows Forms does not
    /// directly use. This static field is read-only.</summary>
    /// <filterpriority>1</filterpriority>
    MetafilePict,
    /// <summary>Specifies the Windows symbolic link format, which Windows Forms does
    /// not directly use. This static field is read-only.</summary>
    /// <filterpriority>1</filterpriority>
    SymbolicLink,
    /// <summary>Specifies the Windows Data Interchange Format (DIF), which Windows Forms
    /// does not directly use. This static field is read-only.</summary>
    /// <filterpriority>1</filterpriority>
    Dif,
    /// <summary>Specifies the Tagged Image File Format (TIFF), which Windows Forms does
    /// not directly use. This static field is read-only.</summary>
    /// <filterpriority>1</filterpriority>
    Tiff,
    /// <summary>Specifies the standard Windows original equipment manufacturer (OEM)
    /// text format. This static field is read-only.</summary>
    /// <filterpriority>1</filterpriority>
    OemText,
    /// <summary>Specifies the Windows palette format. This static field is read-only.
    /// </summary>
    /// <filterpriority>1</filterpriority>
    Palette,
    /// <summary>Specifies the Windows pen data format, which consists of pen strokes
    /// for handwriting software, Windows Forms does not use this format. This static
    /// field is read-only.</summary>
    /// <filterpriority>1</filterpriority>
    PenData,
    /// <summary>Specifies the Resource Interchange File Format (RIFF) audio format,
    /// which Windows Forms does not directly use. This static field is read-only.</summary>
    /// <filterpriority>1</filterpriority>
    Riff,
    /// <summary>Specifies the wave audio format, which Windows Forms does not directly
    /// use. This static field is read-only.</summary>
    /// <filterpriority>1</filterpriority>
    WaveAudio,
    /// <summary>Specifies the Windows file drop format, which Windows Forms does not
    /// directly use. This static field is read-only.</summary>
    /// <filterpriority>1</filterpriority>
    FileDrop,
    /// <summary>Specifies the Windows culture format, which Windows Forms does not directly
    /// use. This static field is read-only.</summary>
    /// <filterpriority>1</filterpriority>
    Locale,
    /// <summary>Specifies text consisting of HTML data. This static field is read-only.
    /// </summary>
    /// <filterpriority>1</filterpriority>
    Html,
    /// <summary>Specifies text consisting of Rich Text Format (RTF) data. This static
    /// field is read-only.</summary>
    /// <filterpriority>1</filterpriority>
    Rtf,
    /// <summary>Specifies a comma-separated value (CSV) format, which is a common interchange
    /// format used by spreadsheets. This format is not used directly by Windows Forms.
    /// This static field is read-only.</summary>
    /// <filterpriority>1</filterpriority>
    CommaSeparatedValue,
    /// <summary>Specifies the Windows Forms string class format, which Windows Forms
    /// uses to store string objects. This static field is read-only.</summary>
    /// <filterpriority>1</filterpriority>
    StringFormat,
    /// <summary>Specifies a format that encapsulates any type of Windows Forms object.
    /// This static field is read-only.</summary>
    /// <filterpriority>1</filterpriority>
    Serializable,
}

我知道它可能太多了,但包装后它应该看起来像:
在此处输入图像描述

然后将该类用作:

    static void Main(string[] args)
    {

        ClipboardMonitor.Start();

        ClipboardMonitor.OnClipboardChange += new ClipboardMonitor.OnClipboardChangeEventHandler(ClipboardMonitor_OnClipboardChange);

        Console.Read();

        ClipboardMonitor.Stop(); // do not forget to stop


        
    }

    static void ClipboardMonitor_OnClipboardChange(ClipboardFormat format, object data)
    {
        Console.WriteLine("Clipboard changed and it has the format: "+format.ToString());
    }

The only reference you need to add is to windows forms in your wpf application. I created a wrapper to the functionality I found on the internet.

Most of the examples do more stuff than what I needed so I decided to create my own class. I like to isolate the problems so this class just listens when the clipboard changes and tells you the type of data that is on the clipboard. For example is it text? an image? or what?

Anyways here is my wrapper:

using System;
using System.Windows.Forms;
using System.Threading;
using System.Runtime.InteropServices;

public static class ClipboardMonitor 
{
    public delegate void OnClipboardChangeEventHandler(ClipboardFormat format, object data);
    public static event OnClipboardChangeEventHandler OnClipboardChange;

    public static void Start()
    {
        ClipboardWatcher.Start();
        ClipboardWatcher.OnClipboardChange += (ClipboardFormat format, object data) =>
        {
            if (OnClipboardChange != null)
                OnClipboardChange(format, data);
        };
    }

    public static void Stop()
    {
        OnClipboardChange = null;
        ClipboardWatcher.Stop();
    }
    
    class ClipboardWatcher : Form
    {
        // static instance of this form
        private static ClipboardWatcher mInstance;

        // needed to dispose this form
        static IntPtr nextClipboardViewer;

        public delegate void OnClipboardChangeEventHandler(ClipboardFormat format, object data);
        public static event OnClipboardChangeEventHandler OnClipboardChange;

        // start listening
        public static void Start()
        {
            // we can only have one instance if this class
            if (mInstance != null)
                return;

            Thread t = new Thread(new ParameterizedThreadStart(x =>
            {
                Application.Run(new ClipboardWatcher());
            }));
            t.SetApartmentState(ApartmentState.STA); // give the [STAThread] attribute
            t.Start();
        }

        // stop listening (dispose form)
        public static void Stop()
        {
            mInstance.Invoke(new MethodInvoker(() =>
            {
                ChangeClipboardChain(mInstance.Handle, nextClipboardViewer);
            }));
            mInstance.Invoke(new MethodInvoker(mInstance.Close));

            mInstance.Dispose();

            mInstance = null;
        }

        // on load: (hide this window)
        protected override void SetVisibleCore(bool value)
        {
            CreateHandle();

            mInstance = this;

            nextClipboardViewer = SetClipboardViewer(mInstance.Handle);

            base.SetVisibleCore(false);
        }

        [DllImport("User32.dll", CharSet = CharSet.Auto)]
        public static extern IntPtr SetClipboardViewer(IntPtr hWndNewViewer);

        [DllImport("User32.dll", CharSet = CharSet.Auto)]
        public static extern bool ChangeClipboardChain(IntPtr hWndRemove, IntPtr hWndNewNext);

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern int SendMessage(IntPtr hwnd, int wMsg, IntPtr wParam, IntPtr lParam);

        // defined in winuser.h
        const int WM_DRAWCLIPBOARD = 0x308;
        const int WM_CHANGECBCHAIN = 0x030D;

        protected override void WndProc(ref Message m)
        {
            switch (m.Msg)
            {
                case WM_DRAWCLIPBOARD:
                    ClipChanged();
                    SendMessage(nextClipboardViewer, m.Msg, m.WParam, m.LParam);
                    break;

                case WM_CHANGECBCHAIN:
                    if (m.WParam == nextClipboardViewer)
                        nextClipboardViewer = m.LParam;
                    else
                        SendMessage(nextClipboardViewer, m.Msg, m.WParam, m.LParam);
                    break;

                default:
                    base.WndProc(ref m);
                    break;
            }
        }

        static readonly string[] formats = Enum.GetNames(typeof(ClipboardFormat));

        private void ClipChanged()
        {
            IDataObject iData = Clipboard.GetDataObject();

            ClipboardFormat? format = null;

            foreach (var f in formats)
            {
                if (iData.GetDataPresent(f))
                {
                    format = (ClipboardFormat)Enum.Parse(typeof(ClipboardFormat), f);
                    break;
                }
            }

            object data = iData.GetData(format.ToString());

            if (data == null || format == null)
                return;

            if (OnClipboardChange != null)
                OnClipboardChange((ClipboardFormat)format, data);
        }


    }
}

public enum ClipboardFormat : byte
{
    /// <summary>Specifies the standard ANSI text format. This static field is read-only.
    /// </summary>
    /// <filterpriority>1</filterpriority>
    Text,
    /// <summary>Specifies the standard Windows Unicode text format. This static field
    /// is read-only.</summary>
    /// <filterpriority>1</filterpriority>
    UnicodeText,
    /// <summary>Specifies the Windows device-independent bitmap (DIB) format. This static
    /// field is read-only.</summary>
    /// <filterpriority>1</filterpriority>
    Dib,
    /// <summary>Specifies a Windows bitmap format. This static field is read-only.</summary>
    /// <filterpriority>1</filterpriority>
    Bitmap,
    /// <summary>Specifies the Windows enhanced metafile format. This static field is
    /// read-only.</summary>
    /// <filterpriority>1</filterpriority>
    EnhancedMetafile,
    /// <summary>Specifies the Windows metafile format, which Windows Forms does not
    /// directly use. This static field is read-only.</summary>
    /// <filterpriority>1</filterpriority>
    MetafilePict,
    /// <summary>Specifies the Windows symbolic link format, which Windows Forms does
    /// not directly use. This static field is read-only.</summary>
    /// <filterpriority>1</filterpriority>
    SymbolicLink,
    /// <summary>Specifies the Windows Data Interchange Format (DIF), which Windows Forms
    /// does not directly use. This static field is read-only.</summary>
    /// <filterpriority>1</filterpriority>
    Dif,
    /// <summary>Specifies the Tagged Image File Format (TIFF), which Windows Forms does
    /// not directly use. This static field is read-only.</summary>
    /// <filterpriority>1</filterpriority>
    Tiff,
    /// <summary>Specifies the standard Windows original equipment manufacturer (OEM)
    /// text format. This static field is read-only.</summary>
    /// <filterpriority>1</filterpriority>
    OemText,
    /// <summary>Specifies the Windows palette format. This static field is read-only.
    /// </summary>
    /// <filterpriority>1</filterpriority>
    Palette,
    /// <summary>Specifies the Windows pen data format, which consists of pen strokes
    /// for handwriting software, Windows Forms does not use this format. This static
    /// field is read-only.</summary>
    /// <filterpriority>1</filterpriority>
    PenData,
    /// <summary>Specifies the Resource Interchange File Format (RIFF) audio format,
    /// which Windows Forms does not directly use. This static field is read-only.</summary>
    /// <filterpriority>1</filterpriority>
    Riff,
    /// <summary>Specifies the wave audio format, which Windows Forms does not directly
    /// use. This static field is read-only.</summary>
    /// <filterpriority>1</filterpriority>
    WaveAudio,
    /// <summary>Specifies the Windows file drop format, which Windows Forms does not
    /// directly use. This static field is read-only.</summary>
    /// <filterpriority>1</filterpriority>
    FileDrop,
    /// <summary>Specifies the Windows culture format, which Windows Forms does not directly
    /// use. This static field is read-only.</summary>
    /// <filterpriority>1</filterpriority>
    Locale,
    /// <summary>Specifies text consisting of HTML data. This static field is read-only.
    /// </summary>
    /// <filterpriority>1</filterpriority>
    Html,
    /// <summary>Specifies text consisting of Rich Text Format (RTF) data. This static
    /// field is read-only.</summary>
    /// <filterpriority>1</filterpriority>
    Rtf,
    /// <summary>Specifies a comma-separated value (CSV) format, which is a common interchange
    /// format used by spreadsheets. This format is not used directly by Windows Forms.
    /// This static field is read-only.</summary>
    /// <filterpriority>1</filterpriority>
    CommaSeparatedValue,
    /// <summary>Specifies the Windows Forms string class format, which Windows Forms
    /// uses to store string objects. This static field is read-only.</summary>
    /// <filterpriority>1</filterpriority>
    StringFormat,
    /// <summary>Specifies a format that encapsulates any type of Windows Forms object.
    /// This static field is read-only.</summary>
    /// <filterpriority>1</filterpriority>
    Serializable,
}

I know it might be to much but but after wrapping it it should look like:
enter image description here

And then you use the class as:

    static void Main(string[] args)
    {

        ClipboardMonitor.Start();

        ClipboardMonitor.OnClipboardChange += new ClipboardMonitor.OnClipboardChangeEventHandler(ClipboardMonitor_OnClipboardChange);

        Console.Read();

        ClipboardMonitor.Stop(); // do not forget to stop


        
    }

    static void ClipboardMonitor_OnClipboardChange(ClipboardFormat format, object data)
    {
        Console.WriteLine("Clipboard changed and it has the format: "+format.ToString());
    }
旧情勿念 2024-11-24 06:33:31

我能找到的只是一个用 C#/VB.NET 编写的 剪贴板监视器。我看到了 WPF 和 WinForms,所以我假设这是一个可行的选择。

涉及 pinvoking user32 dll 中的一些方法。

编辑

在编辑时,上面的原始链接已损坏。这是 archive.org 快照

All I could find was a Clipboard Monitor written in C#/VB.NET. I see WPF and WinForms, so I assume this is a viable options.

Involves pinvoking some methods from the user32 dll.

EDIT

At the time of edit, the original link above is broken. Here's an archive.org snapshot

吐个泡泡 2024-11-24 06:33:31

但是,在这两个操作之间,还可以进行另一个操作
更改剪贴板内容的操作。

当应用程序调用 OpenClipboard() 时,其他应用程序不能使用剪贴板。一旦锁定剪贴板的应用程序调用 CloseClipboard(),任何应用程序都可以使用并锁定剪贴板。

当任何应用程序修改
剪贴板?

是的。请参阅 API SetClipboardViewer() 以及消息 WM_DRAWCLIPBOARD 和 WM_CHANGECBCHAIN。

更多信息请参见:http://msdn.microsoft.com/en-us/library/ms649016(v=vs.85).aspx#_win32_Adding_a_Window_to_the_Clipboard_Viewer_Chain

However, between these two operations, it is possible for another
operation to change the content of the clipboard.

When an application calls OpenClipboard(), no other application can use the clipboard. Once the application that has locked the clipboard calls CloseClipboard(), then any application can then use and lock the clipboard.

Is there a way to be notified when any application modifies the
clipboard?

Yes. See the API SetClipboardViewer() and the messages WM_DRAWCLIPBOARD and WM_CHANGECBCHAIN.

More info here: http://msdn.microsoft.com/en-us/library/ms649016(v=vs.85).aspx#_win32_Adding_a_Window_to_the_Clipboard_Viewer_Chain

つ可否回来 2024-11-24 06:33:31

这是我几年前写的一篇文章,详细介绍了剪贴板甚至通过 Windows API 进行监控:
http://www.clipboardextender.com/developing-clipboard-aware -programs-for-windows/6
请特别注意“常见错误”部分。几乎没有人第一次就能正确地做到这一点。

Here is a write-up that I did a few years ago, detailing clipboard even monitoring via the Windows API:
http://www.clipboardextender.com/developing-clipboard-aware-programs-for-windows/6
Please pay particular attention to the "common mistakes" section. Hardly anyone does this correctly the first time.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文