tags:

views:

292

answers:

2

Hi,

I've built a dialogbox with a RichTextBox and I'd like to have the following behaviour:

I've got the focus (cursor) in the RichTextBox. When the ENTER key is pressed, then there should be a new line in the rich edit control created. The ENTER should NOT close the dialog box [as it does now :-( ].

Any Idea ?

+4  A: 

If the form's AcceptButton property is assigned, referencing a button on the form, this will intercept the enter key presses. Make sure that the form does not have any AcceptButton assigned, and the text box should receive the enter key presses and behave as expected.

Update: If you want to have the behaviour of the AcceptButton and have the RichTextBox receiving the enter key presses when focused you can achieve this in two different ways. One is to set the KeyPreview property of the form to true, and adding the following code to the KeyPress event handler of the form:

private void Form_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar == (char)Keys.Enter && this.ActiveControl != theRichTextBox)
    {
        this.DialogResult = DialogResult.OK;
    }
}

The other approach is to have the AcceptButton property assigned, pointing out a button (that in turn has its DialogResult property set to OK). Then you can add event handlers for the Enter and Leave events for the RichTextBox control that will temporarily un-assign the AcceptButton property of the form:

private void RichTextBox_Enter(object sender, EventArgs e)
{
    this.AcceptButton = null;
}

private void RichTextBox_Leave(object sender, EventArgs e)
{
    this.AcceptButton = btnAccept;
}
Fredrik Mörk
It won't intercept a multiline edit control.
James L
@TopBanana: I just tried it out; it does, both with the regular text box and the RichTextBox controls (both with MultiLine = true).
Fredrik Mörk
@Frederik you're absolutely correct. Try AcceptsReturn=true as well. Sorry, I don't have an IDE to hand.
James L
@TopBanana: AcceptsReturn=true works well together with AcceptButton. Doesn't seem to be available on the RichTextBox though, unfortunately (it has AcceptsTab, but not AcceptsReturn)...
Fredrik Mörk
This solved my problem as well. Thanks!
John at CashCommons
A: 

You mean RichTextBox right? You need to set the AcceptsReturn property true.

James L