tags:

views:

448

answers:

3

Hi,

I want to have this feature in my C# program: When the user do Ctrl+C or Copy anywhere (i.e. when the clipboard content changes), my program will get notified, and check whether the content met certain criteria, if so, become the active program, and process the content, etc.

I can get the contents out from System.Windows.Forms.Clipboard, however, I don't know how to monitor the content changes from the Clipboard.

Cheers,

EDIT: If using Vista or later, use AddClipboardFormatListener as in John Knoeller's answer, for XP, have to use the older, more fragile SetClipboardViewer API, as in the accepted answer.

+4  A: 

You can do this with pinvoke to the Win32 API AddClipboardFormatListener

The listener is a window handle (Form.Handle), and the form will be notified of changes with a WM_CLIPBOARDUPDATE notification

It is a more robust replacement for the older SetClipboardViewer API.

John Knoeller
Thanks. but on the msdn page, the minimum OS requirement for this API is Vista. is that true? (I'm still under XP though. in fact, my users will be using XP, too.)
Weiming
Yes, minimum requirement is Vista. If you are on XP then you have no choice than to use SetClipboarViewer. Be aware that SetClipboardViewer is fragile, although you should have no problems if _your_ code is correct and you are the _only_ viewer.
John Knoeller
Ok, I will be very cautious. Your answer would otherwise be the best. Thanks!
Weiming
+2  A: 

You could use SetClipboardViewer provided by win32 API (through p/invoke).

Here is a page which contains code to set one up in C#: http://www.codeguru.com/csharp/.net/net_general/tipstricks/article.php/c7315/

Moron
SetClipboardViewer is an fragile, older API, you should not be using it in new code. use AddClipboardFormatListener instead.
John Knoeller
+1  A: 

The Win32 API contains a function SetClipboardViewer.

Here is a pretty good (from a quick glance) write up.

BioBuckyBall
that's a good example, too. Thanks!
Weiming