以文本方式查看主题

-  中文XML论坛 - 专业的XML技术讨论区  (http://bbs.xml.org.cn/index.asp)
--  『 Dot NET,C#,ASP,VB 』  (http://bbs.xml.org.cn/list.asp?boardid=43)
----  C#中获取窗口句柄的方法 及 遍历所有窗口句柄  (http://bbs.xml.org.cn/dispbbs.asp?boardid=43&rootid=&id=76535)


--  作者:卷积内核
--  发布时间:8/29/2009 11:15:00 AM

--  C#中获取窗口句柄的方法 及 遍历所有窗口句柄
C#可调用API接口来获取窗口句柄,代码如下

using  System;
using  System.Runtime.InteropServices;
namespace  tstfindwindow
{
///  <summary>
///  Class1  的摘要说明。
///  </summary>
class  Class1
{
    [DllImport( "User32.dll ")]
    public  static  extern  System.IntPtr  FindWindowEx(  System.IntPtr  parent  ,  System.IntPtr  childe  ,      string  strclass  ,string  strname  );
    ///  <summary>
    ///  应用程序的主入口点。
    ///  </summary>
    [STAThread]
    static  void  Main(string[]  args)
    {
    //
    //  TODO:  在此处添加代码以启动应用程序
    //
    IntPtr p=FindWindowEx(System.IntPtr.Zero,System.IntPtr.Zero,null,"窗口标题");  
    }
}


遍历所有窗口句柄
using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Collections.Generic;

class CSharpAPIsDemo
{
    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;
    }

    public WindowInfo[] GetAllDesktopWindows()
    {
        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);
                    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);

        return wndList.ToArray();
    }
}


W 3 C h i n a ( since 2003 ) 旗 下 站 点
苏ICP备05006046号《全国人大常委会关于维护互联网安全的决定》《计算机信息网络国际联网安全保护管理办法》
46.875ms