如何在C#中创建MessageBox?

时间:2008-09-08 04:00:55

标签: c# .net

我刚刚第一次安装了C#,乍一看它似乎与VB6非常相似。我决定先尝试制作一个'Hello,World!'。 UI版。

我从表单设计器开始,创建了一个名为“Click Me!”的按钮。继续双击它并输入

MessageBox("Hello, World!");

我收到以下错误:

MessageBox是'type',但用作'变量'

很公平,似乎在C#MessageBox中是一个Object。我尝试了以下

MessageBox a = new MessageBox("Hello, World!");

我收到以下错误: MessageBox不包含带“1”参数的构造函数

现在我很难过。请帮忙。

8 个答案:

答案 0 :(得分:42)

MessageBox.Show还会返回一个DialogResult,如果你在那里放一些按钮,就意味着你可以让它返回用户点击的内容。大多数时候我写的是

if (MessageBox.Show("Do you want to continue?", "Question", MessageBoxButtons.YesNo) == MessageBoxResult.Yes) {
     //some interesting behaviour here
}

我觉得这有点笨拙,但它完成了工作。

有关您可以在此处使用的其他枚举选项,请参阅https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.dialogresult

答案 1 :(得分:20)

代码摘要:

using System.Windows.Forms;

...

MessageBox.Show( "hello world" );

此外(as per this other stack post):在Visual Studio中,在“解决方案树”中展开项目,右键单击“引用”,“添加引用”,在“框架”选项卡上选择System.Windows.Forms。这将使MessageBox与上面使用的System.Windows.Forms引用一起工作。

答案 2 :(得分:9)

它是MessageBox类的静态函数,执行此操作的简单方法是使用

MessageBox.Show("my message");
System.Windows.Forms类中的

。您可以在这个here的msdn页面上找到更多信息。除此之外,您还可以控制消息框文本,标题,默认按钮和图标。由于您没有指定,如果您尝试在网页中执行此操作,则应该查看触发javascript警报(“我的消息”);或确认(“我的问题”);功能

答案 3 :(得分:6)

尝试以下代码:

MessageBox.Show("Test Information Message", "Caption", MessageBoxButtons.OK, MessageBoxIcon.Information);

答案 4 :(得分:1)

此外,您可以使用MessageBox OKCancel选项,但需要许多代码。 if阻止用于OKelse阻止用于Cancel。这是代码:

if (MessageBox.Show("Are you sure you want to do this?", "Question", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
{
    MessageBox.Show("You pressed OK!");
}
else
{
    MessageBox.Show("You pressed Cancel!");
}

您还可以使用MessageBox YesNo选项:

if (MessageBox.Show("Are you sure want to doing this?", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
    MessageBox.Show("You are pressed Yes!");
}
else
{
    MessageBox.Show("You are pressed No!");
}

答案 5 :(得分:0)

这是您可以放入消息框的一些内容。享受
MessageBox.Show("Enter the text for the message box",
"Enter the name of the message box",
(Enter the button names e.g. MessageBoxButtons.YesNo),
(Enter the icon e.g. MessageBoxIcon.Question),
(Enter the default button e.g. MessageBoxDefaultButton.Button1)

可以找到更多信息here

答案 6 :(得分:0)

我收到同样的错误' System.Windows.Forms.MessageBox'是一种'类型'但即使使用:

,也会像“变量”一样使用
MessageBox.Show("Hello, World!");

我想我的无效语法的初始尝试会导致某种错误,我最终通过在" MessageBox.Show"之间添加一个空格来修复它。和方括号():

MessageBox.Show ("Hello, World!");

现在使用原始语法而没有额外空间再次起作用:

MessageBox.Show("Hello, World!");

答案 7 :(得分:-1)

System.Windows.Forms课程中,您可以在MSDN页面上找到更多内容。除此之外,您还可以控制消息框文本,标题,默认按钮和图标。由于您没有指定,如果您尝试在网页中执行此操作,则应该查看触发javascript alert("my message");confirm("my question");函数。

相关问题