c# WinForms can you get the NumericUpDown text area

蓝咒 提交于 2019-12-19 12:03:47

问题


Is it possible to get the text area of a NumericUpDown control? I'm looking to get it's size so that I can mask it with a panel. I don't want the user to be able to edit AND select the text. Is this possible? Or is there another way of covering up the text in the text box?

Thanks.


回答1:


You can get this by using a Label control instead of the baked-in TextBox control. Add a new class to your project and paste the code shown below. Compile. Drop the new control from the top of the toolbox onto your form.

using System;
using System.Windows.Forms;

class UpDownLabel : NumericUpDown {
    private Label mLabel;
    private TextBox mBox;

    public UpDownLabel() {
        mBox = this.Controls[1] as TextBox;
        mBox.Enabled = false;
        mLabel = new Label();
        mLabel.Location = mBox.Location;
        mLabel.Size = mBox.Size;
        this.Controls.Add(mLabel);
        mLabel.BringToFront();
    }

    protected override void UpdateEditText() {
        base.UpdateEditText();
        if (mLabel != null) mLabel.Text = mBox.Text;
    }
}



回答2:


If you want do disallow manual editing, you can just set ReadOnly property to true.

updown.ReadOnly = true;

If you want to disallow selecting too (I wonder why you need this), you can use reflection. I don't think there's better way, because the field upDownEdit is internal field of UpDownBase.

FieldInfo editProp = updown.GetType().GetField("upDownEdit", BindingFlags.Instance | BindingFlags.NonPublic);
TextBox edit = (TextBox)editProp.GetValue(updown);
edit.Enabled = false;



回答3:


Set the ReadOnly property to true, that's all.




回答4:


The 'proper' way to do this is to create an Up-Down control and a Label (the label can't be selected or edited). However, the authors of Windows Forms, in their infinite wisdom, have decided that we don't need the Up-Down control and so they didn't provide a .NET wrapper for one. They decided that the only reason we could ever want an Up-Down control is when paired with a TextBox control.

The Up-Down control is simple enough to create a light wrapper if you want to go this route: http://msdn.microsoft.com/en-us/library/bb759880.aspx

Edit 1

[snip]

Edit 2

I blogged about it here: http://tergiver.wordpress.com/2010/11/05/using-the-up-down-control-in-windows-forms/



来源:https://stackoverflow.com/questions/4059241/c-sharp-winforms-can-you-get-the-numericupdown-text-area

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