c# WinForm TextBox 输入框 输入限制 (整数, 浮点数)

限制整数

private void TextBoxInteger_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar != '\b' && !Char.IsDigit(e.KeyChar))
            {
                e.Handled = true;
            }
            else if(e.KeyChar == '-' && ((TextBox)sender).Text.Length > 1)
            {
                e.Handled = true;
            }
        }

      

限制浮点数

private void TextBoxFloat_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar != 8 && !Char.IsDigit(e.KeyChar) && e.KeyChar != 0x2E)
    {
        e.Handled = true;
    }

    if (e.KeyChar == '.')   //允许输入回退键
    {
        TextBox tb = sender as TextBox;

        if (tb.Text == "")
        {
            tb.Text = "0.";
            tb.Select(tb.Text.Length, 0);
            e.Handled = true;
        }
        else if (tb.Text.Contains("."))
        {
            e.Handled = true;
        }
        else
        {
            e.Handled = false;
        }
    }

}
C#中,WinForms(Windows Forms)是用于创建Windows桌面应用程序的图形用户界面的一个架。对话输入框通常是通过控件中的`MessageBox`类来实现的,它允许开发者显示一个简单的对话来向用户提供信息,或者请求用户输入。 在WinForms应用程序中,一个对话输入框可以使用`InputBox`方法,这是`MessageBox`类的一个扩展方法,不属于标准的WinForms库,通常是由第三方库或者开发者自定义实现的。这个方法允许用户输入文本,并且可以指定输入框的标题、文本和默认输入值。 下面是一个简单的例子,展示了如何在WinForms应用程序中使用自定义的`InputBox`方法来获取用户输入: ```csharp // 自定义InputBox方法 public static string InputBox(string prompt, string title = "输入", string defaultValue = "") { string result = string.Empty; using (var form = new FormInputBox(prompt, title, defaultValue)) { var resultDialog = form.ShowDialog(); if (resultDialog == DialogResult.OK) { result = form.TextBoxInput.Text; } } return result; } // 窗体类,用于显示输入对话 internal class FormInputBox : Form { private TextBox TextBoxInput; private Label LabelPrompt; public FormInputBox(string prompt, string title, string defaultValue) { // 设置窗体的标题和大小 this.Text = title; this.Size = new Size(300, 150); // 创建标签和文本 LabelPrompt = new Label(); TextBoxInput = new TextBox(); LabelPrompt.Text = prompt; TextBoxInput.Text = defaultValue; // 将控件添加到窗体中 this.Controls.Add(LabelPrompt); this.Controls.Add(TextBoxInput); } } ``` 在上述代码中,`InputBox`方法创建了一个自定义的窗体`FormInputBox`,其中包含一个标签`Label`和一个文本`TextBox`。用户可以在文本输入信息,然后点击确定按钮返回输入的字符串。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值