C#之Winfrom自定义输入框对话框。

如果你需要一个带有输入框的对话框,并在输入完成后接收输入的值,你可以使用自定义窗体来实现。

以下是一个示例代码:

创建一个继承自 Form 的自定义窗体类,命名为 InputDialogForm,并将窗体上放置一个文本框(TextBox)和一个确定按钮(Button)。
public class InputDialogForm : Form
{
    
    
    private TextBox textBox;
    private Button confirmButton;

    public string UserInput {
    
     get; private set; }

    public InputDialogForm()
    {
    
    
        InitializeComponents();
    }

    private void InitializeComponents()
    {
    
    
        textBox = new TextBox();
        textBox.Location = new Point(10, 10);
        textBox.Size = new Size(200, 20);

        confirmButton = new Button();
        confirmButton.Location = new Point(10, 40);
        confirmButton.Text = "确定";
        confirmButton.Click += ConfirmButton_Click;

        Controls.Add(textBox);
        Controls.Add(confirmButton);

        FormBorderStyle = FormBorderStyle.FixedDialog;
        StartPosition = FormStartPosition.CenterScreen;
        AcceptButton = confirmButton;
        Text = "输入框";
        ClientSize = new Size(220, 80);
        MaximizeBox = false;
    }

    private void ConfirmButton_Click(object sender, EventArgs e)
    {
    
    
        UserInput = textBox.Text;
        DialogResult = DialogResult.OK;
    }
}

在你的程序中,在需要触发输入框的地方添加一个按钮或其他事件处理器。例如,你可以在按钮点击事件中执行相应的代码和逻辑。

private void Button_Click(object sender, EventArgs e)
{
    
    
    using (InputDialogForm inputDialog = new InputDialogForm())
    {
    
    
        if (inputDialog.ShowDialog() == DialogResult.OK)
        {
    
    
            string userInput = inputDialog.UserInput;
            if (ValidateInput(userInput))
            {
    
    
                // 输入验证通过后,继续执行后面的代码
                ContinueExecution();
            }
            else
            {
    
    
                // 输入验证失败,可以进行相应的处理(如提示错误信息)
                ShowErrorMessage();
            }
        }
    }
}

private bool ValidateInput(string userInput)
{
    
    
    // 进行输入验证的逻辑,根据需求自定义
    // 返回 true 表示验证通过,返回 false 表示验证失败
    if (!string.IsNullOrEmpty(userInput))
    {
    
    
        return true;
    }
    return false;
}

private void ContinueExecution()
{
    
    
    // 在输入验证通过后,继续执行后面的代码
    // 可以在这里编写需要执行的逻辑
}

private void ShowErrorMessage()
{
    
    
    // 在输入验证失败时,可以弹出错误提示框或进行其他处理
    MessageBox.Show("输入验证失败,请重新输入。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}

通过以上步骤,你可以在 WinForms 程序中创建一个带有输入框的自定义窗体,并在点击确定按钮后获取用户输入的值。确保根据实际需求修改输入验证逻辑和错误处理方式。

猜你喜欢

转载自blog.csdn.net/csdn2990/article/details/132100254