P/Invoke功能 :在Windows Form 程序中调用Windows API

 

如何在Windows Form 程序中调用Windows API的函数,下面通过一个例子学习一下吧。

例子:利用Windows API 的FindWindow函数找到指定的窗口,在利用SendMessage函数发送WM_CLOSE消息关闭该窗口。

  

 

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.Windows.Forms;

 

namespace EnterAsTab

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }

 

        private void button1_Click(object sender, EventArgs e)

        {

            var p = NativeAPI.FindWindow(null, textBox1.Text);

            if(p != null)

            {

                NativeAPI.SendMessage(p, NativeAPI.WM_CLOSE, 0, 0);

            }

        }

 

        public class NativeAPI

        {

            public static uint WM_CLOSE = 0x0010;

 

            [DllImport("user32.dll",CharSet = CharSet.Auto)]

            public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

 

            [DllImport("user32.dll", EntryPoint = "SendMessage")]

            public static extern bool SendMessage(IntPtr hWnd, uint Msg, int wParam, int lParam);

        }

    }

}

运行一下:

     先启动一个计算器程序,然后再改程序的文本框中输入"计算器"后按entry close windows 按钮。计算器程序关闭了。

posted @ 2009-02-10 16:08  anya  阅读(398)  评论(0编辑  收藏  举报