首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

C#调用API有关问题

2013-04-07 
C#调用API问题using Systemusing System.Collections.Genericusing System.Linqusing System.Textusin

C#调用API问题

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.IO;
namespace 遍历所有窗体_获取句柄和窗体名称
{
    class Program
    {
        private delegate bool WNDENUMPROC(IntPtr hWnd, int lParam);
    
        [DllImport("user32.dll")]
        private static extern bool EnumWindows(WNDENUMPROC lpEnumFunc, int lParam);
        //[DllImport("user32.dll")]
        //private static extern IntPtr FindWindowW(string lpClassName, string lpWindowName);
     
        [DllImport("user32.dll")]
        private static extern int GetWindowTextW(IntPtr hWnd, [MarshalAs(UnmanagedType.LPWStr)]StringBuilder lpString, int nMaxCount);
     
        [DllImport("user32.dll")]
        private static extern int GetClassNameW(IntPtr hWnd, [MarshalAs(UnmanagedType.LPWStr)]StringBuilder lpString, int nMaxCount);
    
        public struct WindowInfo
        {
            public IntPtr hWnd;
            public string szWindowName;
            public string szClassName;
        }
        static void Main(string[] args)
        {
            List<WindowInfo> wndList = new List<WindowInfo>();
            //enum all desktop windows
            EnumWindows(delegate(IntPtr hWnd, int lParam)//这里不明白啊
            {
                WindowInfo wnd = new WindowInfo();
                StringBuilder sb = new StringBuilder(256);//动态的字符串
                //get hwnd
                wnd.hWnd = hWnd;
                //get window name
                GetWindowTextW(hWnd, sb, sb.Capacity);
          [code=csharp]      wnd.szWindowName = sb.ToString();
                //get window class


                GetClassNameW(hWnd, sb, sb.Capacity);
                wnd.szClassName = sb.ToString();
                //add it into list
                wndList.Add(wnd);
                return true;


            } , 0);
        }
    }
}[/code]
  EnumWindows(delegate(IntPtr hWnd, int lParam)这里的delegate(IntPtr hWnd, int lParam)原本应该是一个回调函数。这里用委托代替。什么意思?这委托都没有和方法绑定啊。。。。不明白
[code=csharp]
[/code] c#
[解决办法]
调用EnumWindows,参数是委托WNDENUMPROC, 
 {                 
WindowInfo wnd = new WindowInfo();  
StringBuilder sb = new StringBuilder(256);//动态的字符串                 
//get hwnd                 
wnd.hWnd = hWnd;                 
//get window name                 
GetWindowTextW(hWnd, sb, sb.Capacity);                 
wnd.szWindowName = sb.ToString();                 
//get window class                 
GetClassNameW(hWnd, sb, sb.Capacity);                 
wnd.szClassName = sb.ToString();                 
//add it into list                 
wndList.Add(wnd);                 
return true; 

            }
类似于委托绑定的方法
[解决办法]
大括弧里就是函数实体,这个就是匿名委托
[解决办法]
回调函数在C#中使用,就是定义一个委托。

热点排行