你会如何​​禁用.NET WinForms控件不改变自己的外表?自己的、你会、控件、不改变

2023-09-04 09:36:20 作者:金刚互撸娃

比方说,我有一个控制,我想prevent它进行编辑。

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

设置控制为False的Enabled属性将工作,但控制的外观也会随之改变,通常是一个难以读懂了黑灰色字体。当可读性仍然是重要的,这是一个真正的问题。

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;

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

但不幸的是这并不适用于所有的控制工作(如单选按钮)

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

另一种解决方案是让Enabled属性不变,并订阅像这样的焦点事件(但这不是一个真正的完美的解决方案)

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;
    }

你有没有看到解决这一问题的其他途径? (我的意思是现实世界的解决方案;当然你也可以捕获控制的截图并显示拷贝过来的控制...:P)

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)

推荐答案

有一种说法,与标准的Windows行为干预是混淆了用户,但撇开我已经看到了这一点之前完成,但更常用的C ++。你也可以继承的控制和处理自己的油漆消息。当控制的启用只是委托绘制基类。当控制的残疾人,你可以让基类绘制自己​​,然后做在上面的一些自定义绘制,也可以只画了整个事情youself。我强烈推荐的第一种选择。

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.