Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public MainWindow()
- {
- InitializeComponent();
- this.DataContext = new ViewModel(System.Windows.Window wnd);
- }
- public ViewModel(System.Windows.Window wnd)
- {
- InitCBViewer(wnd);
- }
- private void InitCBViewer(System.Windows.Window wnd)
- {
- WindowInteropHelper wih = new WindowInteropHelper(wnd);
- hWndSource = HwndSource.FromHwnd(wih.Handle);
- hWndSource.AddHook(this.WinProc); // start processing window messages
- hWndNextViewer = Win32.SetClipboardViewer(hWndSource.Handle); // set this window as a viewer
- }
- private void InitCBViewer()
- {
- WindowInteropHelper wih = new WindowInteropHelper(this);
- hWndSource = HwndSource.FromHwnd(wih.Handle);
- hWndSource.AddHook(this.WinProc); // start processing window messages
- hWndNextViewer = Win32.SetClipboardViewer(hWndSource.Handle); // set this window as a viewer
- }
- private void CloseCBViewer()
- {
- // remove this window from the clipboard viewer chain
- Win32.ChangeClipboardChain(hWndSource.Handle, hWndNextViewer);
- hWndNextViewer = IntPtr.Zero;
- hWndSource.RemoveHook(this.WinProc);
- }
- private IntPtr WinProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
- {
- switch (msg)
- {
- case Win32.WM_CHANGECBCHAIN:
- if (wParam == hWndNextViewer)
- {
- // clipboard viewer chain changed, need to fix it.
- hWndNextViewer = lParam;
- }
- else if (hWndNextViewer != IntPtr.Zero)
- {
- // pass the message to the next viewer.
- Win32.SendMessage(hWndNextViewer, msg, wParam, lParam);
- }
- break;
- case Win32.WM_DRAWCLIPBOARD:
- // clipboard content changed
- this.DisplayContent(); // calls a function to do something with the data on the clipboard
- // pass the message to the next viewer.
- Win32.SendMessage(hWndNextViewer, msg, wParam, lParam);
- break;
- }
- return IntPtr.Zero;
- }
- internal static class Win32
- {
- /// <summary>
- /// The WM_DRAWCLIPBOARD message notifies a clipboard viewer window that
- /// the content of the clipboard has changed.
- /// </summary>
- internal const int WM_DRAWCLIPBOARD = 0x0308;
- /// <summary>
- /// A clipboard viewer window receives the WM_CHANGECBCHAIN message when
- /// another window is removing itself from the clipboard viewer chain.
- /// </summary>
- internal const int WM_CHANGECBCHAIN = 0x030D;
- [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
- internal static extern IntPtr SetClipboardViewer(IntPtr hWndNewViewer);
- [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
- internal static extern bool ChangeClipboardChain(IntPtr hWndRemove, IntPtr hWndNewNext);
- [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
- internal static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);
- }
Add Comment
Please, Sign In to add comment