I am making a cloud clipboard application which syncs copied texts across sessions in real time using SignalR. I use the following code to listen to and react to clipboard events:
private async void OnLoaded(object sender, RoutedEventArgs e)
{
_windowHandle = new WindowInteropHelper(this).Handle;
RegisterHotKey(_windowHandle, 0, MOD_SHIFT | MOD_ALT, VK_Z);
ComponentDispatcher.ThreadFilterMessage += new ThreadMessageEventHandler(ComponentDispatcherThreadFilterMessage);
AddClipboardFormatListener(_windowHandle);
HwndSource.FromHwnd(_windowHandle)?.AddHook(WndProc);
Hide();
}
And the following is the implementation of the WndProc function:
private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
if (msg == WM_CLIPBOARDUPDATE)
{
handled = true;
_clipboardPage.OnClipboardChanged();
}
return IntPtr.Zero;
}
The issue I am running into is that if two instances of the application are running on a host computer, and a VM (I have tried with HyperV with Win 11 host and Win Server 2022 VM), when a user does a copy, both the clipboards get the event, and both of them react and sync with each other resulting in two instances of copied items (2 UI elements, whereas 1 is desired).
Is there a way I can distinguish in which machine (host or VM) the copy operation was performed so that only that machine’s application can react and sync with other sessions. If not, please advice on how I can change my current approach to satisfy this case, if at all.
I am trying to mimic the Windows clipboard (Windows key + V) functionality as close as possible.
I have noticed if I put one of the applications on a breakpoint in the if (msg == WM_CLIPBOARDUPDATE)
line of the WndProc method, only 1 UI element appears, I assume this is because the other application has set the handled = true
causing this application to ignore it. However, trying to achieve the same faking a delay using Thread.Sleep() did not work.