VB.NET的InputBox在C#中有什么版本?

178

VB.NET的InputBox在C#中有哪个版本?

11个回答

270

Microsoft.VisualBasic 中添加一个引用,InputBoxMicrosoft.VisualBasic.Interaction 命名空间中:


using Microsoft.VisualBasic;
string input = Interaction.InputBox("Prompt", "Title", "Default", x_coordinate, y_coordinate);

prompt仅有第一个参数是必填项


4
InputBox不支持原生蒙版输入。您需要自行创建一个输入表单。 - Ozgur Ozcitak
6
只需导入 using Microsoft.VisualBasic,然后您就可以编写 Interaction.InputBox() - lost_in_the_source
4
我已经至少搜索了10次,每次都得到同样的答案。如果可以的话,我会再次点赞。谢谢! - C4d
1
注意:这在 .NET Core 3.1 中不起作用。 (https://github.com/dotnet/runtime/issues/1162) - M.M
1
对于.NET Framework,您可以使用PasswordChar来掩盖输入:https://learn.microsoft.com/en-us/dotnet/desktop/winforms/controls/how-to-create-a-password-text-box-with-the-windows-forms-textbox-control - phoenix
显示剩余3条评论

140

动态创建对话框。您可以根据自己的喜好进行自定义。

请注意,除了winform之外,这里没有外部依赖。

private static DialogResult ShowInputDialog(ref string input)
    {
        System.Drawing.Size size = new System.Drawing.Size(200, 70);
        Form inputBox = new Form();

        inputBox.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
        inputBox.ClientSize = size;
        inputBox.Text = "Name";

        System.Windows.Forms.TextBox textBox = new TextBox();
        textBox.Size = new System.Drawing.Size(size.Width - 10, 23);
        textBox.Location = new System.Drawing.Point(5, 5);
        textBox.Text = input;
        inputBox.Controls.Add(textBox);

        Button okButton = new Button();
        okButton.DialogResult = System.Windows.Forms.DialogResult.OK;
        okButton.Name = "okButton";
        okButton.Size = new System.Drawing.Size(75, 23);
        okButton.Text = "&OK";
        okButton.Location = new System.Drawing.Point(size.Width - 80 - 80, 39);
        inputBox.Controls.Add(okButton);

        Button cancelButton = new Button();
        cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
        cancelButton.Name = "cancelButton";
        cancelButton.Size = new System.Drawing.Size(75, 23);
        cancelButton.Text = "&Cancel";
        cancelButton.Location = new System.Drawing.Point(size.Width - 80, 39);
        inputBox.Controls.Add(cancelButton);

        inputBox.AcceptButton = okButton;
        inputBox.CancelButton = cancelButton; 

        DialogResult result = inputBox.ShowDialog();
        input = textBox.Text;
        return result;
    }

用法

string input="hede";
ShowInputDialog(ref input);

4
好的,非常简单,我找到了它: inputBox.AcceptButton = okButton; inputBox.CancelButton = cancelButton; 这段代码将确认按钮和取消按钮分别赋值给名为inputBox的输入框。 - F.I.V
14
inputBox.StartPosition = FormStartPosition.CenterParent; 会将对话框居中显示在父窗口上。 - Andrew Cash
3
感谢你编写自己的代码并在这里分享!有些人太懒了,只想轻松得到免费积分。+1。 - Kairan
1
当在单元测试中使用时,该表单不可见。这篇文章会很有帮助。https://dev59.com/qkjSa4cB1Zd3GeqPHrVA - Ray Cheng
5
我更喜欢使用 FormBorderStyle.FixedToolWindow,因为它可以防止窗口被最大化或最小化。 - Nick stands with Ukraine
显示剩余6条评论

116

总之:

  • C#中没有none in C#
  • 您可以通过添加对Microsoft.VisualBasic的引用来使用Visual Basic中的对话框:

    1. 解决方案资源管理器中,右键单击引用文件夹。
    2. 选择添加引用...
    3. .NET选项卡(在较新的Visual Studio版本中为程序集选项卡)中,选择Microsoft.VisualBasic
    4. 点击确定

然后,您可以使用先前提到的代码:

string input = Microsoft.VisualBasic.Interaction.InputBox("Prompt", "Title", "Default", 0, 0);
  • 编写自己的InputBox。
  • 使用别人的

话虽如此,我建议您首先考虑是否需要输入框。对话框并不总是做事情的最佳方式,有时候它们会带来更多的危害而不是好处 - 但这取决于具体情况。


Tomas发布的链接很棒,比Virtual Basic InputBox更好。 - Joe.wang
比使用/subsystem:console好得多...有时您只需要与用户进行非常少量的交互,然后您可以使用它们,而不是让90%的代码用于UI。 - Nulano
我选择了“使用他人”的选项,并对此结果感到满意,来自这个网址:http://www.reflectionit.nl/blog/2003/c-inputbox。我选择它的原因是没有硬编码的大小/位置值。另一个有前途的网址是http://www.csharp-examples.net/inputbox-class/。这两个都有输入文本的验证。在https://dev59.com/6G035IYBdhLWcg3wbPY5中被接受的答案看起来也不错,但不包括输入验证功能。 - Developer63
1
“在C#中没有这个”这种说法至少是误导性的……这些不是语言特性,它们是基本上与语言无关的框架特性。唯一与“不是C#”有关的是命名空间,它只是用于人类消费的标签而已。 - StayOnTarget

9

并没有一个专门的方法。如果你真的想在C#中使用VB InputBox,你可以添加对Microsoft.VisualBasic.dll的引用,然后就能找到它了。

但我建议不要使用它。在我看来,它很丑陋而且过时了。


19
我认为你太客气了。实际上,它比那更丑陋和过时! - BlackWasp
3
在我看来,无法从空的输入字符串中识别出“取消(cancel)”实际上是一个错误。 - Joe.wang

6
返回用户输入的字符串;如果用户点击了取消,则返回空字符串:
    public static String InputBox(String caption, String prompt, String defaultText)
    {
        String localInputText = defaultText;
        if (InputQuery(caption, prompt, ref localInputText))
        {
            return localInputText;
        }
        else
        {
            return "";
        }
    }

String作为ref参数返回,如果用户点击OK,则返回true,如果用户点击Cancel,则返回false

    public static Boolean InputQuery(String caption, String prompt, ref String value)
    {
        Form form;
        form = new Form();
        form.AutoScaleMode = AutoScaleMode.Font;
        form.Font = SystemFonts.IconTitleFont;

        SizeF dialogUnits;
        dialogUnits = form.AutoScaleDimensions;

        form.FormBorderStyle = FormBorderStyle.FixedDialog;
        form.MinimizeBox = false;
        form.MaximizeBox = false;
        form.Text = caption;

        form.ClientSize = new Size(
                    Toolkit.MulDiv(180, dialogUnits.Width, 4),
                    Toolkit.MulDiv(63, dialogUnits.Height, 8));

        form.StartPosition = FormStartPosition.CenterScreen;

        System.Windows.Forms.Label lblPrompt;
        lblPrompt = new System.Windows.Forms.Label();
        lblPrompt.Parent = form;
        lblPrompt.AutoSize = true;
        lblPrompt.Left = Toolkit.MulDiv(8, dialogUnits.Width, 4);
        lblPrompt.Top = Toolkit.MulDiv(8, dialogUnits.Height, 8);
        lblPrompt.Text = prompt;

        System.Windows.Forms.TextBox edInput;
        edInput = new System.Windows.Forms.TextBox();
        edInput.Parent = form;
        edInput.Left = lblPrompt.Left;
        edInput.Top = Toolkit.MulDiv(19, dialogUnits.Height, 8);
        edInput.Width = Toolkit.MulDiv(164, dialogUnits.Width, 4);
        edInput.Text = value;
        edInput.SelectAll();


        int buttonTop = Toolkit.MulDiv(41, dialogUnits.Height, 8);
        //Command buttons should be 50x14 dlus
        Size buttonSize = Toolkit.ScaleSize(new Size(50, 14), dialogUnits.Width / 4, dialogUnits.Height / 8);

        System.Windows.Forms.Button bbOk = new System.Windows.Forms.Button();
        bbOk.Parent = form;
        bbOk.Text = "OK";
        bbOk.DialogResult = DialogResult.OK;
        form.AcceptButton = bbOk;
        bbOk.Location = new Point(Toolkit.MulDiv(38, dialogUnits.Width, 4), buttonTop);
        bbOk.Size = buttonSize;

        System.Windows.Forms.Button bbCancel = new System.Windows.Forms.Button();
        bbCancel.Parent = form;
        bbCancel.Text = "Cancel";
        bbCancel.DialogResult = DialogResult.Cancel;
        form.CancelButton = bbCancel;
        bbCancel.Location = new Point(Toolkit.MulDiv(92, dialogUnits.Width, 4), buttonTop);
        bbCancel.Size = buttonSize;

        if (form.ShowDialog() == DialogResult.OK)
        {
            value = edInput.Text;
            return true;
        }
        else
        {
            return false;
        }
    }

    /// <summary>
    /// Multiplies two 32-bit values and then divides the 64-bit result by a 
    /// third 32-bit value. The final result is rounded to the nearest integer.
    /// </summary>
    public static int MulDiv(int nNumber, int nNumerator, int nDenominator)
    {
        return (int)Math.Round((float)nNumber * nNumerator / nDenominator);
    }

注意: 任何代码都是公共领域的,不需要归属。


公共静态整数 MulDiv(int 数字, int 分子, int 分母) { 返回 (int)(((long)数字 * 分子 + (分母 >> 1)) / 分母); } - Peter Kalef ' DidiSoft
什么是“Toolkit”? - Markus L
1
@markusL 工具包是我的类,它包含了 MulDiv 的实现。你可以看看 Peter 的评论,里面有一个 MulDiv 的示例实现。 - Ian Boyd
Toolkit.ScaleSize是什么? - Jonney
好的。看起来是:Size buttonSize = new Size(MulDiv(50,(int)dialogUnits.Width,4),MulDiv(14,(int)dialogUnits.Height,8)); - Jonney
你能给我发布一下你的工具包类吗?谢谢。jonney3099@gmail.com - Jonney

5
不仅应该将Microsoft.VisualBasic添加到项目的引用列表中,还应该声明using Microsoft.VisualBasic;,这样您只需使用Interaction.Inputbox("...")而不是Microsoft.VisualBasic.Interaction.Inputbox

5
如果您只是使用一次,当原帖发帖人决定不再需要该输入框时,这会增加混乱。此外,这应该是一条评论。 - Joshua Grosso Reinstate CMs

4

添加对 Microsoft.VisualBasic 的引用,并使用此函数:

string response =  Microsoft.VisualBasic.Interaction.InputBox("What's 1+1?", "Title", "2", 0, 0);

最后的两个数字是用来显示输入对话框的X/Y位置。

3

在不添加对Microsoft.VisualBasic的引用的情况下:

// "dynamic" requires reference to Microsoft.CSharp
Type tScriptControl = Type.GetTypeFromProgID("ScriptControl");
dynamic oSC = Activator.CreateInstance(tScriptControl);

oSC.Language = "VBScript";
string sFunc = @"Function InBox(prompt, title, default) 
InBox = InputBox(prompt, title, default)    
End Function
";
oSC.AddCode(sFunc);
dynamic Ret = oSC.Run("InBox", "メッセージ", "タイトル", "初期値");

请参阅以下内容以获取更多信息:
ScriptControl
JScript中的MsgBox
JScript中的Input和MsgBox

.NET 2.0:

string sFunc = @"Function InBox(prompt, title, default) 
InBox = InputBox(prompt, title, default)    
End Function
";

Type tScriptControl = Type.GetTypeFromProgID("ScriptControl");
object oSC = Activator.CreateInstance(tScriptControl);

// https://github.com/mono/mono/blob/master/mcs/class/corlib/System/MonoType.cs
// System.Reflection.PropertyInfo pi = tScriptControl.GetProperty("Language", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.CreateInstance| System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.SetProperty | System.Reflection.BindingFlags.IgnoreCase);
// pi.SetValue(oSC, "VBScript", null);

tScriptControl.InvokeMember("Language", System.Reflection.BindingFlags.SetProperty, null, oSC, new object[] { "VBScript" });
tScriptControl.InvokeMember("AddCode", System.Reflection.BindingFlags.InvokeMethod, null, oSC, new object[] { sFunc });
object ret = tScriptControl.InvokeMember("Run", System.Reflection.BindingFlags.InvokeMethod, null, oSC, new object[] { "InBox", "メッセージ", "タイトル", "初期値" });
Console.WriteLine(ret);

3

你是指 InputBox 吗?只需要在 Microsoft.VisualBasic 命名空间中查找即可。

C# 和 VB.Net 共享一个公共库。如果一种语言可以使用它,另一种语言也可以。


2

我能够通过编写自己的代码来实现这一点。我不喜欢为了一些基本功能而依赖于庞大的库。

表单和设计师:

public partial class InputBox 
    : Form
{

    public String Input
    {
        get { return textInput.Text; }
    }

    public InputBox()
    {
        InitializeComponent();
    }

    private void button2_Click(object sender, EventArgs e)
    {
        DialogResult = System.Windows.Forms.DialogResult.OK;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        DialogResult = System.Windows.Forms.DialogResult.Cancel;
    }

    private void InputBox_Load(object sender, EventArgs e)
    {
        this.ActiveControl = textInput;
    }

    public static DialogResult Show(String title, String message, String inputTitle, out String inputValue)
    {
        InputBox inputBox = null;
        DialogResult results = DialogResult.None;

        using (inputBox = new InputBox() { Text = title })
        {
            inputBox.labelMessage.Text = message;
            inputBox.splitContainer2.SplitterDistance = inputBox.labelMessage.Width;
            inputBox.labelInput.Text = inputTitle;
            inputBox.splitContainer1.SplitterDistance = inputBox.labelInput.Width;
            inputBox.Size = new Size(
                inputBox.Width,
                8 + inputBox.labelMessage.Height + inputBox.splitContainer2.SplitterWidth + inputBox.splitContainer1.Height + 8 + inputBox.button2.Height + 12 + (50));
            results = inputBox.ShowDialog();
            inputValue = inputBox.Input;
        }

        return results;
    }

    void labelInput_TextChanged(object sender, System.EventArgs e)
    {
    }

}

partial class InputBox
{
    /// <summary>
    /// Required designer variable.
    /// </summary>
    private System.ComponentModel.IContainer components = null;

    /// <summary>
    /// Clean up any resources being used.
    /// </summary>
    /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
    protected override void Dispose(bool disposing)
    {
        if (disposing && (components != null))
        {
            components.Dispose();
        }
        base.Dispose(disposing);
    }

    #region Windows Form Designer generated code

    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {
        this.labelMessage = new System.Windows.Forms.Label();
        this.button1 = new System.Windows.Forms.Button();
        this.button2 = new System.Windows.Forms.Button();
        this.labelInput = new System.Windows.Forms.Label();
        this.textInput = new System.Windows.Forms.TextBox();
        this.splitContainer1 = new System.Windows.Forms.SplitContainer();
        this.splitContainer2 = new System.Windows.Forms.SplitContainer();
        ((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).BeginInit();
        this.splitContainer1.Panel1.SuspendLayout();
        this.splitContainer1.Panel2.SuspendLayout();
        this.splitContainer1.SuspendLayout();
        ((System.ComponentModel.ISupportInitialize)(this.splitContainer2)).BeginInit();
        this.splitContainer2.Panel1.SuspendLayout();
        this.splitContainer2.Panel2.SuspendLayout();
        this.splitContainer2.SuspendLayout();
        this.SuspendLayout();
        // 
        // labelMessage
        // 
        this.labelMessage.AutoSize = true;
        this.labelMessage.Location = new System.Drawing.Point(3, 0);
        this.labelMessage.MaximumSize = new System.Drawing.Size(379, 0);
        this.labelMessage.Name = "labelMessage";
        this.labelMessage.Size = new System.Drawing.Size(50, 13);
        this.labelMessage.TabIndex = 99;
        this.labelMessage.Text = "Message";
        // 
        // button1
        // 
        this.button1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
        this.button1.Location = new System.Drawing.Point(316, 126);
        this.button1.Name = "button1";
        this.button1.Size = new System.Drawing.Size(75, 23);
        this.button1.TabIndex = 3;
        this.button1.Text = "Cancel";
        this.button1.UseVisualStyleBackColor = true;
        this.button1.Click += new System.EventHandler(this.button1_Click);
        // 
        // button2
        // 
        this.button2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
        this.button2.Location = new System.Drawing.Point(235, 126);
        this.button2.Name = "button2";
        this.button2.Size = new System.Drawing.Size(75, 23);
        this.button2.TabIndex = 2;
        this.button2.Text = "OK";
        this.button2.UseVisualStyleBackColor = true;
        this.button2.Click += new System.EventHandler(this.button2_Click);
        // 
        // labelInput
        // 
        this.labelInput.AutoSize = true;
        this.labelInput.Location = new System.Drawing.Point(3, 6);
        this.labelInput.Name = "labelInput";
        this.labelInput.Size = new System.Drawing.Size(31, 13);
        this.labelInput.TabIndex = 99;
        this.labelInput.Text = "Input";
        this.labelInput.TextChanged += new System.EventHandler(this.labelInput_TextChanged);
        // 
        // textInput
        // 
        this.textInput.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) 
        | System.Windows.Forms.AnchorStyles.Right)));
        this.textInput.Location = new System.Drawing.Point(3, 3);
        this.textInput.Name = "textInput";
        this.textInput.Size = new System.Drawing.Size(243, 20);
        this.textInput.TabIndex = 1;
        // 
        // splitContainer1
        // 
        this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill;
        this.splitContainer1.FixedPanel = System.Windows.Forms.FixedPanel.Panel2;
        this.splitContainer1.IsSplitterFixed = true;
        this.splitContainer1.Location = new System.Drawing.Point(0, 0);
        this.splitContainer1.Name = "splitContainer1";
        // 
        // splitContainer1.Panel1
        // 
        this.splitContainer1.Panel1.Controls.Add(this.labelInput);
        // 
        // splitContainer1.Panel2
        // 
        this.splitContainer1.Panel2.Controls.Add(this.textInput);
        this.splitContainer1.Size = new System.Drawing.Size(379, 50);
        this.splitContainer1.SplitterDistance = 126;
        this.splitContainer1.TabIndex = 99;
        // 
        // splitContainer2
        // 
        this.splitContainer2.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) 
        | System.Windows.Forms.AnchorStyles.Left) 
        | System.Windows.Forms.AnchorStyles.Right)));
        this.splitContainer2.IsSplitterFixed = true;
        this.splitContainer2.Location = new System.Drawing.Point(12, 12);
        this.splitContainer2.Name = "splitContainer2";
        this.splitContainer2.Orientation = System.Windows.Forms.Orientation.Horizontal;
        // 
        // splitContainer2.Panel1
        // 
        this.splitContainer2.Panel1.Controls.Add(this.labelMessage);
        // 
        // splitContainer2.Panel2
        // 
        this.splitContainer2.Panel2.Controls.Add(this.splitContainer1);
        this.splitContainer2.Size = new System.Drawing.Size(379, 108);
        this.splitContainer2.SplitterDistance = 54;
        this.splitContainer2.TabIndex = 99;
        // 
        // InputBox
        // 
        this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.ClientSize = new System.Drawing.Size(403, 161);
        this.Controls.Add(this.splitContainer2);
        this.Controls.Add(this.button2);
        this.Controls.Add(this.button1);
        this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
        this.MaximizeBox = false;
        this.MinimizeBox = false;
        this.Name = "InputBox";
        this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
        this.Text = "Title";
        this.TopMost = true;
        this.Load += new System.EventHandler(this.InputBox_Load);
        this.splitContainer1.Panel1.ResumeLayout(false);
        this.splitContainer1.Panel1.PerformLayout();
        this.splitContainer1.Panel2.ResumeLayout(false);
        this.splitContainer1.Panel2.PerformLayout();
        ((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).EndInit();
        this.splitContainer1.ResumeLayout(false);
        this.splitContainer2.Panel1.ResumeLayout(false);
        this.splitContainer2.Panel1.PerformLayout();
        this.splitContainer2.Panel2.ResumeLayout(false);
        ((System.ComponentModel.ISupportInitialize)(this.splitContainer2)).EndInit();
        this.splitContainer2.ResumeLayout(false);
        this.ResumeLayout(false);

    }

    #endregion

    private System.Windows.Forms.Label labelMessage;
    private System.Windows.Forms.Button button1;
    private System.Windows.Forms.Button button2;
    private System.Windows.Forms.Label labelInput;
    private System.Windows.Forms.TextBox textInput;
    private System.Windows.Forms.SplitContainer splitContainer1;
    private System.Windows.Forms.SplitContainer splitContainer2;
}

使用方法:

String output = "";

result = System.Windows.Forms.DialogResult.None;

result = InputBox.Show(
    "Input Required",
    "Please enter the value (if available) below.",
    "Value",
    out output);

if (result != System.Windows.Forms.DialogResult.OK)
{
    return;
}

请注意,这展示了一些自动调整大小的功能,以根据您要求显示的文本量保持美观。我知道它缺少花哨和炫耀,但对于面临同样困境的人来说,这是一个坚实的步骤。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接