Change clipboard contents when clipboard changes

I do it in C #, but I guess it is not a language specific problem ...

I have a sample code for determining how the contents of the clipboard changes. Now I want to change the text that was just copied (strip some tags) and replace the clipboard text with fixed.

But if I setDataObject () when I found that the contents of the clipboard have changed, it will create a message that the contents of the clipboard have changed again. In theory, I think it sounds like an infinite loop (in practice, for some reason, it doesn't).

What is the strategy to execute this modification once and send a message to the clipboard monitoring chain?


PS As a test I'm running, but what's going on is the Clipboard.SetDataObject .. line gets called twice. I don't understand why, I expect this to do it endlessly.

case Win32.Msgs.WM_DRAWCLIPBOARD:

    String clipboardText = GetClipboardText();
    if (!String.IsNullOrEmpty(clipboardText))
    {
        Clipboard.SetDataObject("test( " + clipboardText + " )!");
    }

    Win32.User32.SendMessage(_ClipboardViewerNext, m.Msg, m.WParam, m.LParam);

      

+2


source to share


3 answers


Unfortunately, every time you set Clipboard data with Clipboard.SetDataObject, you will "redraw" the clipboard as you change its contents.

The best way to handle this situation is to make your routine check the contents of the clipboard, and only set it if you actually change the clipboard text.



In your case, you are saying that you are removing some tags. Just check the clipboardText line before and after your subroutine, and if the line hasn't changed, don't set it again.

Thus, the first time, it will disable the tags, then reset. Then fire again, see if there is any change, not reset the clipboard data.

+1


source


To prevent recursion, you should only actually set the clipboard text if there are tags for the markup.



To explain the behavior, I would assume that it is WM_DRAWCLIPBOARD

not dispatched recursively, which means that if the clipboard changes during notification WM_DRAWCLIPBOARD

, it will no longer be sent.

+1


source


In fact, there is a much better way to avoid an infinite loop, which works even in cases where you do not change the contents of the clipboard, and therefore you cannot compare if you have changed it or not.

When you encounter a WM_DRAWCLIPBOARD GetClipboardOwner message that will return the handle to the window that changed the handle. Once you have a handle, you can get the process that owns the window. If the process is different from your process, process the clipboard, otherwise the clipboard was modified by you, so ignore it.

+1


source







All Articles