在 .net 控制台应用程序中显示消息框

41
在.net c#或vb的控制台应用程序中如何显示消息框? 类似以下内容:
 Console.WriteLine("Hello World");
 MessageBox.Show("Hello World");

或者。
Console.WriteLine("Hello")
MsgBox("Hello")

分别使用C#和VB语言,这可行吗?

4个回答

52

我们可以在控制台应用程序中显示消息框。但是首先,请在您的VB.NET或C#控制台应用程序中包含此引用。

System.Windows.Forms;

参考:

在vb.net程序中添加引用:右键单击(在解决方案资源管理器中)项目名称->然后添加引用->然后选择.Net->然后选择System.Windows.Forms.
在c#程序中添加引用:右键单击解决方案资源管理器中显示的项目文件夹,然后选择添加引用->.Net ->选择System.Windows.Forms。

然后您可以使用以下代码编写c#控制台应用程序:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace ConsoleApplication6
{
    class Program
    {
        static void Main(string[] args)
        {


            MessageBox.Show("Hello World");
        }
    }
}

对于vb.net应用程序,您可以在包含上述引用后简单编写代码

Module Module1

    Sub Main()
        MsgBox("Hello")
        Console.ReadKey()


    End Sub

End Module

参考此回答,对相关问题进行了调整。


由于代码依赖于引用,请将添加引用说明置于顶部。 - Hkachhia

33
要在控制台应用程序中使用简单的消息框,您可以按照以下步骤进行操作。
  1. 创建一个具有以下属性的属性:

     using System.Runtime.InteropServices;
    
     [DllImport("User32.dll", CharSet = CharSet.Unicode)]
     public static extern int MessageBox(IntPtr h, string m, string c, int type);
    
  2. 使用该属性调用消息框:

     using System;
     using System.Runtime.InteropServices;
    
     namespace AllKeys
     {
         public class Program
         {
             [DllImport("User32.dll", CharSet = CharSet.Unicode)]
             public static extern int MessageBox(IntPtr h, string m, string c, int type);
    
             public static void Main(string[] args)
             {
                 MessageBox((IntPtr)0, "Your Message", "My Message Box", 0);
             }
         }
     }
    

我认为这个答案必须被接受,因为我们不需要将Windows窗体应用程序的依赖项添加到控制台应用程序中(例如使用System.Windows.Forms;)。 - Ramil Aliyev 007

4
在C#项目中添加引用“PresentationFramework”。接下来,在需要MessageBox的类中添加。
using System.Windows;

你也可以这样调用MessageBox类,而不使用using

System.Windows.MessageBox.Show("Stackoverflow");

3

对于 .NET 5.NET 6 =>

  1. 按照常规方式创建控制台应用程序。

  2. 使用以下之一更新.csproj中的TargetFramework:

    <TargetFramework>net5.0-windows</TargetFramework>

    <!--OR-->

    <TargetFramework>net6.0-windows</TargetFramework>

  3. 在.csproj中添加此内容:

    <UseWPF>true</UseWPF>

    <!-- AND/OR -->

    <UseWindowsForms>true</UseWindowsForms>

  4. 编译应用程序,以便更新引用的.NET dlls。

  5. 对于WPF消息框,在代码文件顶部添加using System.Windows;,对于Windows Forms消息框,在代码文件顶部添加using System.Windows.Forms;,然后只需调用MessageBox.Show("...")


参考:https://learn.microsoft.com/zh-cn/dotnet/core/project-sdk/msbuild-props-desktop - Siavash Mortazavi
另外,如果您想隐藏控制台窗口,这里有解决方案:https://dev59.com/DW865IYBdhLWcg3wW9VE - Siavash Mortazavi

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