Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would you disable .net Winforms Controls without changing their appearance?

Tags:

c#

.net

winforms

Let's say I've got a control and I want to prevent it from being edited.

Setting the Enabled property of the control to False will work but the control appearance will change accordingly, usually to a difficult to read black over gray font. When readability is still important, this is a real problem.

For a TextBox, there are a few obvious fixes :

Textbox1.BackColor = Color.White;

or

Textbox1.ReadOnly= true; // instead of setting Enabled to false

but unfortunately this won't work for every controls (eg radio buttons)

Another solution is to let the Enabled property untouched, and to subscribe to the focus event like this (but this isn't a really elegant solution)

    this.Textbox1.Enter += new System.EventHandler(this.Textbox1_Enter);

    private void Textbox1_Enter(object sender, EventArgs e)
    {
      Textbox1.FindForm().ActiveControl = null;
    }

Have you seen other ways of dealing with this problem? (and I mean real world solutions ; of course you can capture a screenshot of the control and display the copy over the control...:p)

like image 322
Brann Avatar asked Jan 27 '09 17:01

Brann


People also ask

How do I remove a form control?

To remove controls from a collection programmaticallyRemove the event handler from the event. In Visual Basic, use the RemoveHandler Statement keyword; in Visual C#, use the -= Operator (C# Reference). Use the Remove method to delete the desired control from the panel's Controls collection.

How do I hide winform?

If you Don't want the user to be able to see the app at all set this: this. ShowInTaskbar = false; Then they won't be able to see the form in the task bar and it will be invisible.

How do I stop multiple windows forms from opening in C#?

Solution 2 NET: Show and ShowDialog. If you have multiple copies appearing then it is not the use of either that is the problem - it is that you are constructing new instances instead of using the same instance each time. private MyForm myForm; Do not assign it a value.


1 Answers

There is an argument that interfering with standard Windows behaviour is confusing for the user, but that aside I have seen this done before, although more commonly in C++. You can subclass the control and handle paint messages yourself. When the control's enabled just delegate the drawing to the base class. When the control's disabled you can either let the base class draw itself and then do some custom drawing over the top or you can just draw the entire thing youself. I'd strongly recommend the first of these options.

like image 152
Stu Mackellar Avatar answered Sep 28 '22 11:09

Stu Mackellar