Clipboard Listener Event Triggered Twice

I want to save the changes to my clipboard. so I registered my application to get all the changes that occur with the clipboard.

Using

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

and then

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

The problem is this: When copying text from an application such as visual studio or firefox, the OnClipboardChanged () function will be called twice or 3 times.

I think this application will write data to the clipboard with different formats, so the function is called more than once. But how can I prevent the same data from being saved because OnClipboardChanged () is called more than once?

+3
source share
2 answers

/ . . Excel 24 .
():

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

, , :

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

. , LAST , " " . 500 .

+7

private int _i = 0;
private int i
{
    get
    {
        async void setI()
        {
            await Task.Run(() =>
            {
                Thread.Sleep(20);
                i = 0;
            }
            );
        }
        setI();
        return _i;
    }
    set
    {
        _i = value;
    }
}
private IntPtr HwndHandler(IntPtr hwnd, int msg, IntPtr wparam, IntPtr lparam, ref bool handled)
{
    if (msg == WM_CLIPBOARDUPDATE)
    {
        if(i<1)
        {
            this.ClipboardUpdate?.Invoke(this, new EventArgs());
            i++;
        }
    }
    handled = false;
    return IntPtr.Zero;
}
0

All Articles