Darj
Darj

Reputation: 1403

C#: How to deselect and defocus textbox?

I'm writing a simple calc-based app in C# WinForms. My issue is that I have textbox to display results which cannot be clicked/focused because buttons are binded to keyboard. Textbox has to have ContextMenuStrip, but only this action should be handled within textbox. Also this app requirement is that it cannot have any focusable controls. Something like Windows' Calc result box. Any advice?

Upvotes: 4

Views: 7689

Answers (6)

ghiboz
ghiboz

Reputation: 8003

to defocus simply do this:

TextBox.Select(0, 0);

Upvotes: 0

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236308

Create custom text box:

public class TextBoxWithoutFocus : TextBox
{
    private const int WM_SETFOCUS = 0x7;

    protected override void WndProc(ref Message m)
    {
        if (m.Msg == WM_SETFOCUS)
            return;

        base.WndProc(ref m);
    }
}

That's all. Text box will never receive a focus (actually it will receive focus, but it will not change its look). Also consider suppress WM_CHAR message (0x102) if you want to disable user input.

UPDATE (trick you can use with buttons):

public class ButtonWithoutFocus : Button
{
    public ButtonWithoutFocus()
    {
        SetStyle(ControlStyles.Selectable, false);
    }
}

Upvotes: 4

vguzmanp
vguzmanp

Reputation: 825

Make it a label, not a textBox. You can set dimensions and background so it looks like a textBox, and it has ContextMenuStrip.

Upvotes: 2

Rick Gittins
Rick Gittins

Reputation: 1138

Try both TextBox.Enabled = False; and TextBox1.ReadOnly = True;

Upvotes: 1

Likurg
Likurg

Reputation: 2760

Try this

TextBox1.ReadOnly = True;

Upvotes: 0

zimdanen
zimdanen

Reputation: 5626

Does TextBox.Enabled = false meet your needs?

Upvotes: 0

Related Questions