Display Windows Message Box from Console App

Written by stevey on July 27th, 2010

In a Console app, you normally write out message to screen using Console.WriteLine(). How should I display a Windows message box like we usually do in a Windows Form app?

Call the MessageBox method from user32.dll COM API is one of the methods I learned, and here were how it was done (no need to set reference to user32.dll; just do DllImport):

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Runtime.InteropServices;

 

namespace ComInterop

{

class Message

{

 

public static void ShowMessage(string msg,string caption)

{

 

//MessageBox(new IntPtr(0), msg, caption, 0); //type=0 only show OK button

MsgBox(new IntPtr(0), msg, caption, 1); //Type=1 shows both OK and Cancel button

 

 

}

[DllImport(“user32.dll”)]

private static extern int MessageBox(IntPtr hwnd, String text, String caption, uint type);

//if want to use different method name other than what’s given in the type lib, use EntryPoint attribute

[DllImport(“user32.dll”, EntryPoint = “MessageBox”)]

private static extern int MsgBox(IntPtr hwnd, String text, String caption, uint type);

}

 

class Program

{

static void Main(string[] args)

{

//user32.dll DLLImport

Message.ShowMessage(“This method used DllImport”, “DllImport is Cool”);

}

}

 

}

 

 

Leave a Comment