简体   繁体   中英

Background clipboard monitoring in WPF with MVVM and binding copied context in View

I have been trying to make WPF Windows program (C#). In the UI I have been planning that there will be a list of text which shows what user has copied when the program has been open. So the program collects the copied strings and displays them in the list in the window.

My problem is that I want to do this MVVM way, and I'm not quite familiar with it. The way I'm trying to monitor the users clipboard changes is with this: https://stackoverflow.com/a/33018459/6741346 . I don't know if there is easier or better MVVM version to monitor that clipboard changes?

The problem is that I am unsure how should I make the View Model. I know that I need ObservableCollection and bind it to the View. But I have no idea how can I do it like that, when the user makes the clipboard change, it will update the Observablecollection and then automatically displays the changes to Window's listview for example.

For MVVM you can derive your main window from my ClipboardMonitorWindow class and register a command for Clipboard Update. It works complete without Forms.

using System;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Input;
using System.Windows.Interop;

public class ClipboardMonitorWindow : Window
{
    private const int WM_CLIPBOARDUPDATE = 0x031D;

    private IntPtr windowHandle;

    public event EventHandler ClipboardUpdate;

    protected override void OnInitialized(EventArgs e)
    {
        base.OnInitialized(e);

        windowHandle = new WindowInteropHelper(this).EnsureHandle();
        HwndSource.FromHwnd(windowHandle)?.AddHook(HwndHandler);
        Start();
    }

    public static readonly DependencyProperty ClipboardUpdateCommandProperty =
        DependencyProperty.Register("ClipboardUpdateCommand", typeof(ICommand), typeof(ClipboardMonitorWindow), new FrameworkPropertyMetadata(null));

    public ICommand ClipboardUpdateCommand
    {
        get { return (ICommand)GetValue(ClipboardUpdateCommandProperty); }
        set { SetValue(ClipboardUpdateCommandProperty, value); }
    }

    protected virtual void OnClipboardUpdate()
    { }

    public void Start()
    {
        NativeMethods.AddClipboardFormatListener(windowHandle);
    }

    public void Stop()
    {
        NativeMethods.RemoveClipboardFormatListener(windowHandle);
    }

    private IntPtr HwndHandler(IntPtr hwnd, int msg, IntPtr wparam, IntPtr lparam, ref bool handled)
    {
        if (msg == WM_CLIPBOARDUPDATE)
        {
            // fire event
            this.ClipboardUpdate?.Invoke(this, new EventArgs());
            // execute command
            if (this.ClipboardUpdateCommand?.CanExecute(null) ?? false)
            {
                this.ClipboardUpdateCommand?.Execute(null);
            }
            // call virtual method
            OnClipboardUpdate();
        }
        handled = false;
        return IntPtr.Zero;
    }


    private static class NativeMethods
    {
        [DllImport("user32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool AddClipboardFormatListener(IntPtr hwnd);

        [DllImport("user32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool RemoveClipboardFormatListener(IntPtr hwnd);
    }
}

Depending on how you want the application to work, you may or not not need an ObservableCollection .

If you simply want to see latest content in the clipboard, a simple model that implement INPC will suffice. However, if you see to keep an history of clipboard changes, you will need an ObservableCollection . To update it, just add an handler to ClipboardManager.ClipboardChanged , and make sure you update the ObservableCollection from the UI thread with Application.Current.Dispatcher .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM