Wednesday, August 5, 2009

Easy Way Detect Changes On The Clipboard With Windows API

A recent Windows Forms project required that I copy data from a grid and an associated object with each cell copied. This allows a user to paste the data in the same grid but in a different set of cells.

My problem came when a user would copy data from an external application like Excel, and tries to copy the text into my grid. I had to come up with a way to determine the user was trying to paste something copied from an external program.

There is a great solution using a Windows API called GetClipboardSequenceNumber().

[DllImport("user32.dll")]

static extern uint GetClipboardSequenceNumber();



Using this API allows you top capture the sequence number every time something is copied to the clipboard. Here is the workflow I went through.



1. Capture the sequence number when the mouse or keyboard events are fired



2. When the paste event is fired, check the clipboard sequence and compare it to one saved locally. If the numbers are difference, only paste the text, if they are the same, paste the text and the object.



I put the sequence capture in my Copy method so it’s changed internally every time someone chooses Edit/Copy from the menu, presses CTL-C, or right clicks and selects Copy from a popup menu.



This seems to work pretty well. There really isn’t any code to share other than the knowing which DLL and method to use. Where to store the sequence and how you use it is going to be up to you.

Share this article

0 comments:

Post a Comment

 
Copyright © 2003 - 2014 Thom Allen Weblog • All Rights Reserved.