How to handle Ctrl+V (Pasting into) in a .Net Windows form

Want to override the Ctrl+V keys so that they paste something into your application when a form is the active control? This took me quite a bit of digging around and experimenting before I could finally figure out how to do this.

First of all, you will need to handle the KeyDown event on the form that you want to be pasting things into:


private void frmMain_KeyDown(object sender, KeyEventArgs e)
{

}

This function stub can be generated by going to your form in the design viewer, looking at the properties, and viewing the events, and double clicking next to the KeyDown event.

This will fire every time your form is active and someone presses a key, so make sure you don’t do any real heavy lifting in there. The last thing you want is an application that bogs down every time a user presses any key.

Next, you will need to check to see if the Control key and the V key are being pressed. This is done inside the KeyDown event handler:

if(e.Control == true && e.KeyCode == Keys.V)
{
//Handle pasting here
}

Like the comment says, you put the code to handle pasting of data in there. It is a fairly trivial matter to read out text from the clipboard in .Net. There are plenty of other resources that should be able to help you there.

So why did this take me so long to figure out? Well, the parameter on the KeyPress event handler contains quite a bit of stuff. It contains a list of modifiers that may or may not be pressed, it contains the KeyCode of the key being pressed (which could technically be the Control key itself!), and it contains the KeyValue of the key being pressed. There is also the list of modifier keys (such as Control, Shift, etc.) which are currently pressed that are on the form. This means there is a pile of different ways of checking to see if the Ctrl key and the V key are both being pressed at the same time. After muddling around with things for longer than I should admit, I finally realized that it’s the above combination that actually works. There seems to be a bazillion different combinations, and this one seems to work.

So, your KeyPress event handler should look about like this:


private void frmMain_KeyDown(object sender, KeyEventArgs e)
{

if(e.Control == true && e.KeyCode == Keys.V)
{
PasteFromClipboard(); //where you handle the actual pasting from the clipboard
}

}

I know this snippet will come in handy in the future, at least for me!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s