RichTextBox equivalent of TextBox.AcceptsReturn
I am switching several TextBoxes out for RichTextBoxes to gain some of the cool features.
I had my TextBoxes configured to AcceptReturn so that the enter key will create a new line,开发者_高级运维 rather than leave the control. The RichTextBox does not seem to have this feature.
Is there a simple way to do this, or do I have to capture all keypresses and handle them individually?
Note: This issue occurs only when you set the "AcceptButton" property of the form.
Set the RichTextBox.AcceptsTab to true. For some reason this works for both tabs and the enter key. If you only want the enter keys then you will have to write custom code.
Since Carter pointed out that this only applies if AcceptButton is set, and the other solution suggests deriving the RichTextBox class, I found another simple solution. Just unset AcceptButton for the time that the/a RichTextBox has the focus. Here's a sample code:
private void RichText_Enter(object sender, EventArgs e)
{
AcceptButton = null;
}
private void RichText_Leave(object sender, EventArgs e)
{
AcceptButton = OKActionButton;
}
This assumes that you only have a single AcceptButton and that is unlikely to change. Otherwise you would have to copy some AcceptButton finding logic here or just backup the previous AcceptButton value before setting it to null.
This solution also has the side effect of removing the default border from the actual accept button, indicating to the user that pressing the Enter key now will not activate that button.
The solution is to override IsInputKey
:
protected override bool IsInputKey(Keys keyData)
{
if (
(keyData & ~Keys.Modifiers) == Keys.Tab &&
(keyData & (Keys.Control | Keys.Alt)) == 0
)
return false;
return base.IsInputKey(keyData);
}
After setting AcceptsTab
to true, you ensure that the RichTextBox
processes both the tab and return key. With the IsInputKey
implementation above, we ensure that the Tab and Shift+Tab key never reach the RichTextBox
so they are used for navigation instead.
The above override must be pasted in a class derived from RichTextBox
.
Just change Accept option in Richtextbox Property turn to "true" it will work like a magic
精彩评论