C # calling Win32 API functions

Source: Internet
Author: User

The window API functions can be invoked in C # through the interoperability service using System.Runtime.InteropServices. And by attributes to specify the location of API functions, and how to invoke, for example, We're going to call the function in User32.dll MessageBox (HWnd hwnd,lpctstr lptext,lpctstr lpcaption,uint type)

First, we introduce the name space

Using System.Runtime.InteropServices;

Second, define a static method and specify how it is invoked. The calling method is specified with the key child [DllImport ()].

Such as:

[DllImport ("user32.dll", EntryPoint = "MessageBox", ExactSpelling = False)]

public static extern int MessageBox (int hWnd, string text, string caption, uint type);

The function can then be invoked like a normal function.

The complete code is as follows:

/*
* write by zhanghua
* date:2008/5/28
*
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace NetMeeting.API
{
  public class Win32
  {
    [DllImport("user32.dll", EntryPoint = "MessageBox", ExactSpelling = false)]
    public static extern int MessageBox(int hWnd, string text, string caption, uint type);
  }
}

The client invocation is almost indistinguishable from the C # function, as follows:

using System;
using NetMeeting.API;
class test
{
  public static void Main(string[] agrs)
  {
      Win32.MessageBox(0,"hello ,this is a c# invoke win32 api","test",2);
  }
}

Calls with complex parameters and callback functions we'll talk about it next time.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.