RichTextBox equivalent of TextBox.AcceptsReturn

断了今生、忘了曾经 提交于 2020-01-14 07:25:13

问题


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?


回答1:


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.




回答2:


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.




回答3:


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.




回答4:


Just change Accept option in Richtextbox Property turn to "true" it will work like a magic



来源:https://stackoverflow.com/questions/3268375/richtextbox-equivalent-of-textbox-acceptsreturn

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!