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

Sye*_*ruf 17 .net c# vb.net messagebox console-application

如何在.net c#或vb 控制台应用程序中显示消息框?就像是:

 Console.WriteLine("Hello World");
 MessageBox.Show("Hello World");
Run Code Online (Sandbox Code Playgroud)

要么

Console.WriteLine("Hello")
MsgBox("Hello")
Run Code Online (Sandbox Code Playgroud)

分别在c#和vb中.
可能吗?

Sye*_*ruf 30

我们可以在控制台应用程序中显示一个消息框.但首先在vb.net或c#console应用程序中包含此引用

System.Windows.Forms;
Run Code Online (Sandbox Code Playgroud)

参考:

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

然后你可以为c#console应用程序执行以下代码:

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");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

对于vb.net应用程序,您可以在包含上述参考后简单地编码

Module Module1

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


    End Sub

End Module
Run Code Online (Sandbox Code Playgroud)

这个答案改编成相关问题.


小智 13

要在控制台应用程序中包含一个简单的消息框,您可以按照以下步骤操作.

  1. 创建属性为的属性

使用System.Runtime.InteropServices;

[DllImport("User32.dll", CharSet = CharSet.Unicode)]

public static extern int MessageBox(IntPtr h, string m, string c, int type);
Run Code Online (Sandbox Code Playgroud)
  1. 使用该属性调用消息框.

    MessageBox((IntPtr)0,"asdasds","我的消息框",0);

            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);
                    }
                }
            }
    
    Run Code Online (Sandbox Code Playgroud)


Sia*_*avi 5

对于.NET 5.NET 6 =>

\n
    \n
  1. 以常规方式创建控制台应用程序。

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

    \n

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

    \n

    <!--或-->

    \n

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

    \n
  4. \n
  5. 将其添加到 .csproj:

    \n

    <UseWPF>true</UseWPF>

    \n

    <!--\xc2\xa0AND/OR\xc2\xa0-->

    \n

    <UseWindowsForms>true</UseWindowsForms>

    \n
  6. \n
  7. 编译应用程序,以便更新引用的 .NET dll。

    \n
  8. \n
  9. 对于WPF消息框添加使用System.Windows; 并为 Windows 窗体消息框添加using System.Windows.Forms; 在代码文件的顶部。然后,只需调用MessageBox.Show("...")

    \n
  10. \n
\n