剪贴板侦听器事件被调用两次 [英] clipboard Listener event is being called twice

查看:211
本文介绍了剪贴板侦听器事件被调用两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将更改保存在剪贴板中。所以我注册了我的应用程序以获取剪贴板上发生的所有更改。

i want to save the changes in my clipboard. so i registered my application to get all the changes that happens to the Clipboard.

使用

    [DllImport("User32.dll")]
    protected static extern bool AddClipboardFormatListener(int hwnd);

然后

protected override void WndProc(ref Message m)
    {
switch (m.Msg)
        {
            case WM_CLIPBOARDUPDATE:
                OnClipboardChanged();
                break;
             ...
        }
     }

private void OnClipboardChanged()
{
    if (Clipboard.ContainsText())
        {
         MessageBox.Show(Clipboard.GetText().ToString());
        }
}

问题是:
复制文本时从Visual Studio或firefox之类的应用程序中,有时会调用OnClipboardChanged()函数两次或3次。

The Problem is: When copying text from an application like visual studio or firefox, the OnClipboardChanged() function will be called twice or 3 times sometimes.

我认为这些应用程序会将数据写入剪贴板具有不同的格式,这就是为什么多次调用该函数的原因。
但是,由于多次调用OnClipboardChanged(),我又如何防止保存相同的数据?

I think that those application will write the Data to the clipboard with different formats, this is why the function is called more than once. But how would i prevent saving the same data because OnClipboardChanged() is being called more than once ?

推荐答案

因为他们多次打开/关闭剪贴板。我以前见过如此疯狂。 Excel在复制图表时曾经执行24个单独的操作。

代替此操作(伪代码):

Because they're opening/closing the clipboard multiple times. I've seen such madness before. Excel used to perform 24 separate operations when copying a chart.
Instead of this (pseudocode):

openClipboard
for each format {
  place data on clipboard(format)
}
closeClipboard

他们可能正在这样做:

for each format {
  openClipboard
  place data on clipboard(format)
  closeClipboard
}

更新:常用的缓解策略是避免对每个更新做出反应,并且在经过合理的稳定时间之后没有对剪贴板进行任何通知之后,对LAST更新做出反应。 500ms通常绰绰有余。

Update: The usual mitigation strategy is to avoid reacting to every update, and react to the LAST update after a reasonable "settle time" has elapsed with no further clipboard notifications. 500ms will usually be more than adequate.

这篇关于剪贴板侦听器事件被调用两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆