Search This Blog

Wednesday, November 20, 2013

DllImport Attribute C# Example

C# > InteropServices > DllImport

DllImport Attribute  marks a class method defined in an external dynamic-link library (DLL) not in  .NET assembly.

DllImport attribute is used at run time to call a function exported in an external DLL  outside the control of common language runtime (CLR).


DllImport is helpful when accessing and reusing the functionality of the Win32 application programming interface (API) and  unmanaged codes that are implemented in DLL.

Example:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        [DllImport("User32.dll")]
        public static extern int MessageBox(int h, string m, string c, int type);

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            MessageBox(0, "This is an example of using DLLImport to call a Win32 function", "User32 MessageBox", 0);
        }
    }
}