我正在使用 System.Windows.Forms
,但奇怪的是我没有创建它们的能力。
我如何获得类似于JavaScript提示对话框的东西,而不使用JavaScript?
MessageBox很好,但用户无法输入任何内容。
我希望用户能够输入任何可能的文本输入。
我正在使用 System.Windows.Forms
,但奇怪的是我没有创建它们的能力。
我如何获得类似于JavaScript提示对话框的东西,而不使用JavaScript?
MessageBox很好,但用户无法输入任何内容。
我希望用户能够输入任何可能的文本输入。
您需要创建自己的提示对话框。您可以考虑创建一个类来实现此功能。
public static class Prompt
{
public static string ShowDialog(string text, string caption)
{
Form prompt = new Form()
{
Width = 500,
Height = 150,
FormBorderStyle = FormBorderStyle.FixedDialog,
Text = caption,
StartPosition = FormStartPosition.CenterScreen
};
Label textLabel = new Label() { Left = 50, Top=20, Text=text };
TextBox textBox = new TextBox() { Left = 50, Top=50, Width=400 };
Button confirmation = new Button() { Text = "Ok", Left=350, Width=100, Top=70, DialogResult = DialogResult.OK };
confirmation.Click += (sender, e) => { prompt.Close(); };
prompt.Controls.Add(textBox);
prompt.Controls.Add(confirmation);
prompt.Controls.Add(textLabel);
prompt.AcceptButton = confirmation;
return prompt.ShowDialog() == DialogResult.OK ? textBox.Text : "";
}
}
然后调用它:
string promptValue = Prompt.ShowDialog("Test", "123");
更新:
根据评论和另一个问题,添加了默认按钮(回车键)和初始焦点。
在你的 C# 代码中添加对 Microsoft.VisualBasic
的引用:
string input = Microsoft.VisualBasic.Interaction.InputBox("Prompt",
"Title",
"Default",
0,
0);
添加引用:在项目资源管理器窗口中右键单击“引用”,然后选择“添加引用”,并在列表中选中 VisualBasic。
Microsoft.VisualBasic
中不存在 Interaction
。 - Khalil Khalaf在 Windows Forms 中本身没有这样的东西。
您需要为此创建自己的表单或:
使用 Microsoft.VisualBasic
引用。
Inputbox 是带入 .Net 以保持与 VB6 兼容性的遗留代码 - 所以我建议不要这样做。
Microsoft.VisualBasic.Compatibility
命名空间。Microsoft.VisualBasic
更多地是一组在 .Net 之上的帮助库,与 VB 没有特别的关系。 - Jim Wooley从理论上讲,Bas的答案可能会使你陷入内存问题,因为ShowDialog不会被处理。我认为这是一种更合适的方式。此外,还要提到textLabel在处理较长文本时应该是可读的。
public class Prompt : IDisposable
{
private Form prompt { get; set; }
public string Result { get; }
public Prompt(string text, string caption)
{
Result = ShowDialog(text, caption);
}
//use a using statement
private string ShowDialog(string text, string caption)
{
prompt = new Form()
{
Width = 500,
Height = 150,
FormBorderStyle = FormBorderStyle.FixedDialog,
Text = caption,
StartPosition = FormStartPosition.CenterScreen,
TopMost = true
};
Label textLabel = new Label() { Left = 50, Top = 20, Text = text, Dock = DockStyle.Top, TextAlign = ContentAlignment.MiddleCenter };
TextBox textBox = new TextBox() { Left = 50, Top = 50, Width = 400 };
Button confirmation = new Button() { Text = "Ok", Left = 350, Width = 100, Top = 70, DialogResult = DialogResult.OK };
confirmation.Click += (sender, e) => { prompt.Close(); };
prompt.Controls.Add(textBox);
prompt.Controls.Add(confirmation);
prompt.Controls.Add(textLabel);
prompt.AcceptButton = confirmation;
return prompt.ShowDialog() == DialogResult.OK ? textBox.Text : "";
}
public void Dispose()
{
//See Marcus comment
if (prompt != null) {
prompt.Dispose();
}
}
}
实现:
using(Prompt prompt = new Prompt("text", "caption")){
string result = prompt.Result;
}
通常情况下,将VisualBasic库导入C#程序并不是一个好主意(不是因为它们不能工作,而是出于兼容性,风格和升级能力的考虑),但是您可以调用Microsoft.VisualBasic.Interaction.InputBox()来显示所需的对话框。
如果您能够创建Windows.Forms对象,那将是最好的选择,但是您说您无法这样做。
Microsoft.MakeMyLifeEasierWithAlreadyImplementedMethods
命名空间。 - Cody GrayMicrosoft.VisualBasic.Compatibility
子命名空间,而不是整个 VB.NET。很多“核心”功能都包含在 Microsoft.VisualBasic
命名空间中,它并不会消失。微软已经威胁要停用 VB 6,而不是 VB.NET。他们已经 反复 承诺它不会消失。一些人似乎仍然没有弄清楚其中的区别... - Cody Graypublic partial class TextPrompt : Form
{
public string Value
{
get { return tbText.Text.Trim(); }
}
public TextPrompt(string promptInstructions)
{
InitializeComponent();
lblPromptText.Text = promptInstructions;
}
private void BtnSubmitText_Click(object sender, EventArgs e)
{
Close();
}
private void TextPrompt_Load(object sender, EventArgs e)
{
CenterToParent();
}
}
var t = new TextPrompt(this, "Type the name of the settings file:");
t.ShowDialog()
使用这种方式,代码看起来更加简洁:
根据Bas Brekelmans的工作,我也创建了两个衍生物——"输入"对话框,可以让用户输入文本值和布尔值(TextBox和CheckBox):
public static class PromptForTextAndBoolean
{
public static string ShowDialog(string caption, string text, string boolStr)
{
Form prompt = new Form();
prompt.Width = 280;
prompt.Height = 160;
prompt.Text = caption;
Label textLabel = new Label() { Left = 16, Top = 20, Width = 240, Text = text };
TextBox textBox = new TextBox() { Left = 16, Top = 40, Width = 240, TabIndex = 0, TabStop = true };
CheckBox ckbx = new CheckBox() { Left = 16, Top = 60, Width = 240, Text = boolStr };
Button confirmation = new Button() { Text = "Okay!", Left = 16, Width = 80, Top = 88, TabIndex = 1, TabStop = true };
confirmation.Click += (sender, e) => { prompt.Close(); };
prompt.Controls.Add(textLabel);
prompt.Controls.Add(textBox);
prompt.Controls.Add(ckbx);
prompt.Controls.Add(confirmation);
prompt.AcceptButton = confirmation;
prompt.StartPosition = FormStartPosition.CenterScreen;
prompt.ShowDialog();
return string.Format("{0};{1}", textBox.Text, ckbx.Checked.ToString());
}
}
...以及选择多个选项之一(文本框和组合框)的文本:
public static class PromptForTextAndSelection
{
public static string ShowDialog(string caption, string text, string selStr)
{
Form prompt = new Form();
prompt.Width = 280;
prompt.Height = 160;
prompt.Text = caption;
Label textLabel = new Label() { Left = 16, Top = 20, Width = 240, Text = text };
TextBox textBox = new TextBox() { Left = 16, Top = 40, Width = 240, TabIndex = 0, TabStop = true };
Label selLabel = new Label() { Left = 16, Top = 66, Width = 88, Text = selStr };
ComboBox cmbx = new ComboBox() { Left = 112, Top = 64, Width = 144 };
cmbx.Items.Add("Dark Grey");
cmbx.Items.Add("Orange");
cmbx.Items.Add("None");
Button confirmation = new Button() { Text = "In Ordnung!", Left = 16, Width = 80, Top = 88, TabIndex = 1, TabStop = true };
confirmation.Click += (sender, e) => { prompt.Close(); };
prompt.Controls.Add(textLabel);
prompt.Controls.Add(textBox);
prompt.Controls.Add(selLabel);
prompt.Controls.Add(cmbx);
prompt.Controls.Add(confirmation);
prompt.AcceptButton = confirmation;
prompt.StartPosition = FormStartPosition.CenterScreen;
prompt.ShowDialog();
return string.Format("{0};{1}", textBox.Text, cmbx.SelectedItem.ToString());
}
}
两者都需要相同的引用:
using System;
using System.Windows.Forms;
PromptForTextAndBoolean.ShowDialog("Jazz", "What text should accompany the checkbox?", "Allow Scat Singing");
PromptForTextAndSelection.ShowDialog("Rock", "What should the name of the band be?", "Beret color to wear");
这里的类可以解决上述限制: http://www.codeproject.com/Articles/31315/Getting-User-Input-With-Dialogs-Part-1
我只是下载了源代码并将InputBox.cs复制到我的项目中。
但是我还是很惊讶为什么没有更好的类似工具…… 我唯一的投诉是标题文本不支持换行,因为它使用了一个标签控件。
using System.Drawing;
using System.Windows.Forms;
namespace yourNameSpaceHere
{
public class PopUpBox
{
private static Form prompt { get; set; }
public static string GetUserInput(string instructions, string caption)
{
string sUserInput = "";
prompt = new Form() //create a new form at run time
{
Width = 500, Height = 150, FormBorderStyle = FormBorderStyle.FixedDialog, Text = caption,
StartPosition = FormStartPosition.CenterScreen, TopMost = true
};
//create a label for the form which will have instructions for user input
Label lblTitle = new Label() { Left = 50, Top = 20, Text = instructions, Dock = DockStyle.Top, TextAlign = ContentAlignment.TopCenter };
TextBox txtTextInput = new TextBox() { Left = 50, Top = 50, Width = 400 };
////////////////////////////OK button
Button btnOK = new Button() { Text = "OK", Left = 250, Width = 100, Top = 70, DialogResult = DialogResult.OK };
btnOK.Click += (sender, e) =>
{
sUserInput = txtTextInput.Text;
prompt.Close();
};
prompt.Controls.Add(txtTextInput);
prompt.Controls.Add(btnOK);
prompt.Controls.Add(lblTitle);
prompt.AcceptButton = btnOK;
///////////////////////////////////////
//////////////////////////Cancel button
Button btnCancel = new Button() { Text = "Cancel", Left = 350, Width = 100, Top = 70, DialogResult = DialogResult.Cancel };
btnCancel.Click += (sender, e) =>
{
sUserInput = "cancel";
prompt.Close();
};
prompt.Controls.Add(btnCancel);
prompt.CancelButton = btnCancel;
///////////////////////////////////////
prompt.ShowDialog();
return sUserInput;
}
public void Dispose()
{prompt.Dispose();}
}
}
bool boolTryAgain = false;
do
{
string sTextFromUser = PopUpBox.GetUserInput("Enter your text below:", "Dialog box title");
if (sTextFromUser == "")
{
DialogResult dialogResult = MessageBox.Show("You did not enter anything. Try again?", "Error", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
boolTryAgain = true; //will reopen the dialog for user to input text again
}
else if (dialogResult == DialogResult.No)
{
//exit/cancel
MessageBox.Show("operation cancelled");
boolTryAgain = false;
}//end if
}
else
{
if (sTextFromUser == "cancel")
{
MessageBox.Show("operation cancelled");
}
else
{
MessageBox.Show("Here is the text you entered: '" + sTextFromUser + "'");
//do something here with the user input
}
}
} while (boolTryAgain == true);
这是我的重构版本,可以选择多行/单行
public string ShowDialog(string text, string caption, bool isMultiline = false, int formWidth = 300, int formHeight = 200)
{
var prompt = new Form
{
Width = formWidth,
Height = isMultiline ? formHeight : formHeight - 70,
FormBorderStyle = isMultiline ? FormBorderStyle.Sizable : FormBorderStyle.FixedSingle,
Text = caption,
StartPosition = FormStartPosition.CenterScreen,
MaximizeBox = isMultiline
};
var textLabel = new Label
{
Left = 10,
Padding = new Padding(0, 3, 0, 0),
Text = text,
Dock = DockStyle.Top
};
var textBox = new TextBox
{
Left = isMultiline ? 50 : 4,
Top = isMultiline ? 50 : textLabel.Height + 4,
Multiline = isMultiline,
Dock = isMultiline ? DockStyle.Fill : DockStyle.None,
Width = prompt.Width - 24,
Anchor = isMultiline ? AnchorStyles.Left | AnchorStyles.Top : AnchorStyles.Left | AnchorStyles.Right
};
var confirmationButton = new Button
{
Text = @"OK",
Cursor = Cursors.Hand,
DialogResult = DialogResult.OK,
Dock = DockStyle.Bottom,
};
confirmationButton.Click += (sender, e) =>
{
prompt.Close();
};
prompt.Controls.Add(textBox);
prompt.Controls.Add(confirmationButton);
prompt.Controls.Add(textLabel);
return prompt.ShowDialog() == DialogResult.OK ? textBox.Text : string.Empty;
}