C#带有ComboBox的消息框

8

如何在C# Win Forms应用程序中生成一个消息框,其中显示了一系列可选择的值的组合框以及通常的“Ok”按钮?

我希望能够在调用MessageBox.Show()方法时触发此操作。 我假设需要某种覆盖,但我没有看到任何现有的示例。

6个回答

12

使用自定义的Form,并使用.ShowDialog()方法代替。


3

很抱歉,你不能这样做。Windows MessageBox的功能受到限制。你可以显示一个外观类似的对话框窗口,但如果你使用MessageBox,你将被限制在MessageBox具有的功能上。


2

最近我需要做一个非常简单的问题,而不是创建一个类,我生成了一个带有下拉框和“确定”按钮的简单表单。以下是生成表单、填充数据和获取结果的函数。这很混乱,但对我来说效果很好。

/// <summary>
/// Generate a tiny form that prompts the user for the language to use.
/// </summary>
private void prompt_for_language()
{            
    QuestionForm.Text = "Language";
    Label lbLanguageChoice = new Label();
    lbLanguageChoice.Text = "Choose a Language";
    lbLanguageChoice.Location = new Point(1, 1);
    lbLanguageChoice.Size = new Size(200, lbLanguageChoice.Size.Height);

    ComboBox LanguageChoices = new ComboBox();

    LanguageChoices.Location = new Point(1, lbLanguageChoice.Location.Y + lbLanguageChoice.Height + 5);
    List<string> language_list = LanguageList();
    language_list.Sort();
    for (int loop = 0; loop < language_list.Count; loop++)
        LanguageChoices.Items.Add(language_list[loop]);
    int def = language_list.IndexOf(CurrentLanguage);
    if (def < 0) def = language_list.IndexOf(DefaultLanguage);
    if (def < 0) def = 0;
    if (language_list.Count < 1) return; //we cannot prompt when there are no languages defined
    if (def >= 0) LanguageChoices.SelectedIndex = def;

    Button Done = new Button();
    Done.Click += btnClose_Click;
    Done.Text = "Done";
    Done.Location = new Point(1, LanguageChoices.Location.Y + LanguageChoices.Height + 5); ;
    QuestionForm.Controls.Add(LanguageChoices);
    QuestionForm.Controls.Add(Done);
    QuestionForm.Controls.Add(lbLanguageChoice);
    QuestionForm.FormBorderStyle = FormBorderStyle.FixedDialog;
    QuestionForm.AutoSize = true;
    QuestionForm.Height = Done.Location.Y + Done.Height + 5; //This is too small for the form, it autosizes to "big enough"
    QuestionForm.Width = LanguageChoices.Location.X + LanguageChoices.Width + 5;
    QuestionForm.ShowDialog();
    if (LanguageChoices.SelectedIndex >= 0)
    {
        SetLanguage(LanguageChoices.SelectedItem.ToString());
    }
}

/// <summary>
/// Used by prompt_for_language -> done button. 
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnClose_Click(object sender, EventArgs e)
{
    if(QuestionForm != null)
        QuestionForm.Close();
}

1
为了增加混乱和复杂性,我们可以将Done点击函数包含在创建表单的函数内部: Done.Click += (s, g) => { Button b = (Button)s; Form f = (Form)b.Parent; f.Close(); }; - BouncyTarget

1

0

您需要创建自己的表单,此处是一个教程,介绍了如何创建它,它是用VB.NET编写的,但是非常容易转换成C#。


0
如果消息框不够用,您可能想使用任务对话框。如果您必须支持Windows XP,则不能使用该原生API,但是有足够多的.NET实现适用于Windows Forms和WPF,而且自己实现也相当容易。好处在于,如今用户习惯于任务对话框,而不是自定义消息框。

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