C#,.net 8 console call MessageBox of System.Windows.Forms, and via MessageBox of User32.dll

using System.Runtime.InteropServices;

namespace ConsoleApp6
{
    internal class Program
    {
        //copy from,https://gist.github.com/6rube/34b561827f0805f73742541b8b8bb770
        [DllImport("user32.dll", CharSet = CharSet.Unicode)]
        static extern int MessageBox(IntPtr hWnd, String text, String caption, uint type);
        static void Main(string[] args)
        {
            CallWindowsFormsMessageBox();
            //CallUser32MessageBox();
        }

        static void CallWindowsFormsMessageBox()
        {
            string str = $"{DateTime.Now.ToString("yyyyMMddHHmmssfff")}\n{Guid.NewGuid().ToString("N")}";
            var dialogResult = System.Windows.Forms.MessageBox.Show(str, "System.Windows.Forms.MessageBox", MessageBoxButtons.YesNo,
                 MessageBoxIcon.Question);
            if(dialogResult==DialogResult.Yes)
            {
                Application.Exit();
            }
        }

        static void CallUser32MessageBox()
        {
            string str = $"{DateTime.Now.ToString("yyyyMMddHHmmssfff")}\n{Guid.NewGuid().ToString("N")}";
            MessageBox(new IntPtr(0), str, "MessageBox", 0);
        }
    }
}

 

 

//csproj file
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0-windows</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
    <UseWindowsForms>true</UseWindowsForms>
  </PropertyGroup>
</Project>

 

 

 

 

 

 

posted @ 2024-12-12 22:41  FredGrit  阅读(91)  评论(0)    收藏  举报