Skip to content

Instantly share code, notes, and snippets.

@ozkary
Created July 9, 2019 00:38
Show Gist options
  • Save ozkary/a6690d6c15aa146bcb5ffbda1e1e36f1 to your computer and use it in GitHub Desktop.
Save ozkary/a6690d6c15aa146bcb5ffbda1e1e36f1 to your computer and use it in GitHub Desktop.
Console application to show how to use DLLImport to import methods exposed by an unmanaged dynamic-link library (DLL). This example shows how to call the MessageBox Win32 API Call.
using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
InteropDemo.MessageBox("app", "hello");
}
}
public sealed class InteropDemo
{
private InteropDemo() { }
//adds an ok button to the message box
private const uint MB_OK = (uint)0x00000000L;
//windows handle
private static IntPtr? windowHandle;
// Use DllImport to import the Win32 MessageBox function.
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
private static extern int MessageBox(IntPtr hWnd, string text, string caption, uint type);
// Use to get the window handle
[DllImport("user32.dll", SetLastError = true)]
private static extern IntPtr FindWindow(string className, string windowName);
/// <summary>
/// this is the internal api call
/// </summary>
/// <param name="caption"></param>
/// <param name="text"></param>
public static void MessageBox(String caption, String text)
{
//or use windowHandle if allocated
IntPtr hWnd = windowHandle ?? IntPtr.Zero;
MessageBox(hWnd, caption, text, MB_OK);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment