简体   繁体   中英

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.

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 .

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.

只需将Richtextbox Property中的Accept选项更改为“true”,它就会像魔术一样工作

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM