I want to add to my WPF application the ability to monitor Clipboard changes. But also I want to filter only Clipboard changes that happens in my app. So I wrote the following code in one of the main view models, this VM inherits from
Conductor<IScreen>
of Caliburn.Micro.
The code:
protected override void OnActivate()
{
base.OnActivate();
ScreenExtensions.TryActivate(ChildWindow);
BuildClipboard();
GotoLogin();
}
private void BuildClipboard()
{
_windowHandle = (new WindowInteropHelper(Application.Current.MainWindow)).EnsureHandle();
_hWndSource = HwndSource.FromHwnd(_windowHandle);
_hWndSource.AddHook(new HwndSourceHook(WndProc));
SetClipboardViewer(_windowHandle);
}
private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
try
{
if (_windowHandle == hwnd && msg == WM_DRAWCLIPBOARD)
{
IDataObject iData = Clipboard.GetDataObject();
if (iData.GetDataPresent(DataFormats.Text))
{
/////
}
}
}
catch(Exception
{
///
}
}
protected override void OnDeactivate(bool close)
{
_hWndSource.RemoveHook(new HwndSourceHook(WndProc));
_windowHandle = IntPtr.Zero;
ScreenExtensions.TryDeactivate(ChildWindow, close);
base.OnDeactivate(close);
....
}
I have some problems: First, the line
if (_windowHandle == hwnd && msg == WM_DRAWCLIPBOARD)
does not help to get the behavior I want. For some reason hwnd always have the same int value, even if I copy things from Word and not from my app. Second problem, each time I restart my app, when my app starts it gets to WndProc method with the value of a copy I made before I restarted my app. off curse It's not the behavior I want.
I hope you can help me, Thank you, Anat