Here's a discussion that gives a few different options:
http://dotnet247.com/247reference/msgs/50/250024.aspx
One way that I've done similar things in the past is make a class that derives from NativeWindow, hook into the datagridtextbox's wndproc, and catch/cancel the event from there. It's not a trivial task and may be overkill for this. When I did it, the purpose was to catch paste messages into a certain column so I could do some processing on the data before it was pasted.
Here's the native code class I wrote:
/// <summary>
/// Raises an event when a control receives a paste message
/// </summary>
public class PasteListener: NativeWindow
{
/* usage:
* 1. create a new instance of this object, sending the constructor the control you want to
* watch for a paste event: PasteListener pl = new PasteListener(this.textbox1);
* You have to have one pastelistener for each control, so you may need to create a structure to
* hold them.
* 2. Add your own event handler to handle the paste event:
* pl.Paste += new PasteListener.PasteEventHandler(this.DetectPaste);
* */
private const int WM_PASTE = 0x0302;
public Control myControl;
public delegate void PasteEventHandler(object sender, CancelEventArgs e);
public event PasteEventHandler Paste;
public PasteListener(Control control)
{
control.HandleCreated += new EventHandler(this.OnHandleCreated);
control.HandleDestroyed += new EventHandler(this.OnHandleDestroyed);
this.myControl = control;
}
// Listen for the control's window creation and then hook into it.
internal void OnHandleCreated(object sender, EventArgs e)
{
// Window is now created, assign handle to NativeWindow.
AssignHandle(((Control)sender).Handle);
}
internal void OnHandleDestroyed(object sender, EventArgs e)
{
// Window was destroyed, release hook.
ReleaseHandle();
}
protected override void WndProc(ref Message m)
{
// Listen for paste messages
switch (m.Msg)
{
case WM_PASTE:
{
CancelEventArgs ce = new CancelEventArgs();
OnPaste(ce);
if (ce.Cancel)
base.WndProc(ref m);
break;
}
default:
{
base.WndProc(ref m);
break;
}
}
}
protected void OnPaste(CancelEventArgs e)
{
if (Paste != null)
Paste(this, e);
}
public Control Control
{
get { return myControl; }
}
}
And here's the DataGrid.ControlAdded event handler - where you actually hook up the NativeWindow to the datagridtextbox:
private void Control_Added(object sender, System.Windows.Forms.ControlEventArgs e)
{
if (pnCol.TextBox == e.Control && this.MaterialPasteListener == null)
{
this.MaterialPasteListener = new PasteListener(e.Control);
this.MaterialPasteListener.Paste += new PasteListener.PasteEventHandler(this.DetectPaste);
}
}
Good luck,
-SN