Listen to clipboard changes in a WPF application
To improve the UX, it can be useful to listen to clipboard changes. For instance, you can fill a 2FA code in a text box when the user copies it to the clipboard.
This can be done using the AddClipboardFormatListener
function. Here is a simple example of how to listen to clipboard changes in a WPF application:
First, you need to add the Microsoft.Windows.CsWin32
package to your project. This package generate P/Invoke signatures for Windows APIs.
Shell
dotnet add package Microsoft.Windows.CsWin32
Then, you can add a file named NativeMethods.txt
with the following content:
NativeMethods.txt
AddClipboardFormatListener
WM_CLIPBOARDUPDATE
Finally, you need to call the AddClipboardFormatListener
function and listen to the WM_CLIPBOARDUPDATE
message:
C#
using System.Windows;
using System.Windows.Interop;
using Windows.Win32;
using Windows.Win32.Foundation;
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Loaded += Window_Loaded;
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
if (PInvoke.AddClipboardFormatListener(new HWND(new WindowInteropHelper(this).Handle)))
{
ComponentDispatcher.ThreadFilterMessage += ComponentDispatcher_ThreadFilterMessage;
}
}
private void ComponentDispatcher_ThreadFilterMessage(ref MSG msg, ref bool handled)
{
if (msg.message == PInvoke.WM_CLIPBOARDUPDATE)
{
// Clipboard content has changed
Console.WriteLine(Clipboard.GetText());
}
}
}
Do you have a question or a suggestion about this post? Contact me!
Enjoy this blog?
💖 Sponsor on GitHub