WPF Clipboard Viewer

April 30, 2008

One of the common tasks is to monitor clipboard and perform some actions, when it changes. I encountered such task in WPF. WPF as well as .NET doesn’t have any built in components to solve this task. After some googling i found a great article, which describes how to monitor clipboard in windows form. I am strongly recommended to read this article, because further reading assumes, that you know it.

Why this approach is not possible in WPF? Because WPF Window doesn’t have property Handle and you can’t override WndProc. Seems to be troublesome. First problem can be solved using PresentationSource class. PresentationSource  is another wrapper around windows handle. You can get it using PresentationSource.FromVisual method. Actually, you will be working with HwndSource class, which is derived from PresentationSource. HwndSource has property Handle. So, first problem is solved. What about ovveriding WndProc? I don’t know how to do it in WPF, but i suggest another approach. HwndSource has method AddHook, which allows us to receive all window messages. Thanks to these ideas we can implement Clipboard Viewer in WPF. I called my class ClipBoardViewer, it construts from any HwndSource and expose event ClipBoardTextChanged. Feel free to modify it for your needs.

ClipBoardViewer.vb