我正在使用System.Windows.Forms
,但奇怪的是,我没有能力创建它们。
如何在不使用javascript的情况下获得类似javascript提示符对话框的内容?
MessageBox很不错,但用户无法输入输入。
答案 0 :(得分:240)
您需要创建自己的“提示”对话框。你也许可以为此创建一个类。
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");
<强>更新强>:
根据评论和another question添加了默认按钮(输入密钥)和初始焦点。
答案 1 :(得分:44)
添加对Microsoft.VisualBasic
的引用并将其用于您的C#代码:
string input = Microsoft.VisualBasic.Interaction.InputBox("Prompt",
"Title",
"Default",
0,
0);
答案 2 :(得分:15)
Windows Forms中本身没有这样的东西。
您必须为此创建自己的表单或:
使用Microsoft.VisualBasic
引用。
输入框是传入.Net的遗留代码,用于VB6兼容性 - 所以我建议不要这样做。
答案 3 :(得分:7)
将VisualBasic库导入C#程序通常不是一个好主意(不是因为它们不起作用,而是因为兼容性,样式和升级能力),但您可以调用Microsoft.VisualBasic.Interaction。 InputBox()显示您正在寻找的那种盒子。
如果你可以创建一个Windows.Forms对象,那将是最好的,但你说你做不到。
答案 4 :(得分:4)
其他方式: 假设您有一个TextBox输入类型, 创建一个表单,并将文本框值作为公共属性。
public 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()
这样,代码看起来更干净:
答案 5 :(得分:2)
基于上面的Bas Brekelmans的工作,我还创建了两个派生词 - &gt; “输入”对话框,允许您从用户接收文本值和布尔值(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());
}
}
...和文本以及多个选项之一(TextBox和ComboBox)的选择:
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");
答案 6 :(得分:2)
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()
{
prompt.Dispose();
}
}
实现:
using(Prompt prompt = new Prompt("text", "caption")){
string result = prompt.Result;
}
答案 7 :(得分:1)
Bas Brekelmans的答案非常优雅,简洁。但是,我发现对于实际的应用程序,还需要更多,例如:
这里的类处理这些限制: http://www.codeproject.com/Articles/31315/Getting-User-Input-With-Dialogs-Part-1
我刚下载了源代码并将InputBox.cs复制到我的项目中。
感到惊讶的是,没有更好的东西......我唯一真正的抱怨是因为它使用标签控件所以标题文本不支持换行符。
答案 8 :(得分:0)
这是我的重构版本,可以接受多行/单行
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;
}
答案 9 :(得分:0)
不幸的是,C#仍未在内置库中提供此功能。当前最好的解决方案是使用弹出小表格的方法创建自定义类。 如果您使用的是Visual Studio,则可以通过单击“项目”>“添加类”
来完成此操作将类命名为 PopUpBox (如果愿意,可以稍后重命名),并粘贴以下代码:
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);
此方法检查返回的字符串是否为文本值,空字符串或“取消”(如果单击“取消”按钮,则getUserInput方法将返回“取消”)并采取相应的措施。如果用户没有输入任何内容并单击“确定”,它将告诉用户并询问他们是否要取消或重新输入他们的文本。
后记: 在我自己的实现中,我发现所有其他答案都缺少以下一项或多项内容:
因此,我已经发布了自己的解决方案。我希望有人觉得它有用。感谢Bas和Gideon +评论者的贡献,您帮助我提出了一个可行的解决方案!
答案 10 :(得分:-2)
这是VB.NET中的一个例子
Public Function ShowtheDialog(caption As String, text As String, selStr As String) As String
Dim prompt As New Form()
prompt.Width = 280
prompt.Height = 160
prompt.Text = caption
Dim textLabel As New Label() With { _
.Left = 16, _
.Top = 20, _
.Width = 240, _
.Text = text _
}
Dim textBox As New TextBox() With { _
.Left = 16, _
.Top = 40, _
.Width = 240, _
.TabIndex = 0, _
.TabStop = True _
}
Dim selLabel As New Label() With { _
.Left = 16, _
.Top = 66, _
.Width = 88, _
.Text = selStr _
}
Dim cmbx As New ComboBox() With { _
.Left = 112, _
.Top = 64, _
.Width = 144 _
}
cmbx.Items.Add("Dark Grey")
cmbx.Items.Add("Orange")
cmbx.Items.Add("None")
cmbx.SelectedIndex = 0
Dim confirmation As New Button() With { _
.Text = "In Ordnung!", _
.Left = 16, _
.Width = 80, _
.Top = 88, _
.TabIndex = 1, _
.TabStop = True _
}
AddHandler confirmation.Click, Sub(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())
End Function