以编程方式模拟C#2010中RichTextBox的KeyDown事件
我的窗体上有一个RichTextBox,我想使用RichTextBox的默认行为,如Ctrl + Z(撤消)或其他操作(Ctrl + Y ,Ctrl + X,Ctrl + V)。以编程方式模拟C#2010中RichTextBox的KeyDown事件
如果用户使用快捷键(Ctrl + Z),它是完美的。但是如果用户点击一个ToolStripButton呢?
我如何C#编程的2010年
这里模拟keydown事件的RichTextBox的是,有一些问题的代码段。你能帮助我如何在C#中模拟/ RaiseEvent?
private void tsbUndo_Click(object sender, EventArgs e)
{
rtbxContent_KeyDown(rtbxContent, new KeyEventArgs(Keys.Control | Keys.Z));
}
private void tsbPaste_Click(object sender, EventArgs e)
{
DoPaste();
}
private void DoPaste()
{
rtbxContent.Paste(DataFormats.GetFormat(DataFormats.UnicodeText));
}
private void rtbxContent_KeyDown(object sender, KeyEventArgs e)
{
//if ((Control.ModifierKeys & Keys.Control) == Keys.Control)
if (e.Control)
{
switch (e.KeyCode)
{
// I want my application use my user-defined behavior as DoPaste() does
case Keys.V:
DoPaste();
e.SuppressKeyPress = true;
break;
// I want my application use the default behavior as the RichTextBox control does
case Keys.A:
case Keys.X:
case Keys.C:
case Keys.Z:
case Keys.Y:
e.SuppressKeyPress = false;
break;
default:
e.SuppressKeyPress = true;
break;
}
}
}
谢谢。
的RichTextBox
有一个Undo
方法,将做同样的事情CTRL +ž。您可以在点击ToolStribButton
时致电。还有Copy
和Paste
方法以及CanPaste
方法,可用于启用/禁用对应于粘贴命令的ToolStripButton
。
这样你就不需要模拟任何东西,而是调用产生行为的功能。毕竟,按键只是触发这种行为。
是的,这实际上可以在不编写自定义RichTextBox的情况下完成。而是呼吁RichTextBox的粘贴()方法中,你可以使用SendKeys类,这将触发的关键事件的控制
private void DoPaste()
{
rtbxContent.Focus(); // You should check to make sure the Caret is in the right place
SendKeys.Send("^V"); //^represents CTRL, V represents the 'V' key
}
这当然假定您的数据存储在剪贴板中。
嗨大卫,你的解决方案也适合我。很遗憾,我不能标出两个正确的答案。 SendKeys.Send( “^ V”);相当有用:-) – 2010-09-06 05:37:45
嗨弗雷德里克,你是对的,有相应的方法做我所需要的。 – 2010-09-06 05:36:57