获取没有名称的窗口的句柄

时间:2016-01-26 07:38:55

标签: c#

我使用Findwindow()来获取这样的窗口名称的IntPtr:

[DllImport("user32.dll", SetLastError = true)]
        static extern IntPtr FindWindow(string lpClassName, string lpWindowName);



IntPtr handle = FindWindow(null, WindowName);

if (handle != IntPtr.Zero)
{
  RECT windowRectangle = GetWindowRect(handle);
}

当windowname不为空时这可以工作但是当窗口没有名字时我怎么能这样做?

2 个答案:

答案 0 :(得分:1)

请参阅Jerry Fernholz最初发布的this code sample回答类似问题:

    ...
    using System.Runtime.InteropServices;
    using System.Diagnostics;

    ...

public class foo()
{
    ...

    [DllImport ("user32")]
    internal static extern int GetWindowText (int hWnd, String text, int nMaxCount);

    [DllImport ("user32.dll")]
    public static extern int GetWindowTextLength (int hWnd);

    [DllImport ("user32.dll")]
    public static extern int FindWindow (String text, String class_name);

    [DllImport ("user32.dll")]
    public static extern int FindWindowEx (int parent, int start, String class_name);

    [DllImport ("user32.dll")]
    public static extern int GetWindow (int parent, uint cmd);

    public List<int> FindTitlelessWindows()
    {
        List<int> titleless = new List<int> ();

        Process [] procs = Process.GetProcesses ();
        IntPtr hWnd;

        foreach (Process proc in procs)
        {
            hWnd = proc.MainWindowHandle;
            if (hWnd != IntPtr.Zero)
            {
                TraverseHierarchy (hWnd.ToInt32 (), 0, titleless);

            }
        }

        foreach (int i in titleless)
        {
            System.Console.WriteLine (i);
        }

        return titleless;
    }

    public void TraverseHierarchy (int parent, int child, List<int> titleless)
    {
        String text = "";
        GetWindowText (parent, text, GetWindowTextLength (parent));
        if (String.IsNullOrEmpty (text))
        {
            titleless.Add (parent);
        }

        TraverseChildern (parent, titleless);
        TraversePeers (parent, child, titleless);

    }

    public void TraverseChildern(int handle, List<int> titleless)
    {
        // First traverse child windows
        const uint GW_CHILD = 0x05;
        int child = GetWindow (handle, GW_CHILD);
        if (0 != child)
        {
            TraverseHierarchy (child, 0, titleless);

        }
    }

    public void TraversePeers(int parent, int start, List<int> titleless)
    {
        // Next traverse peers
        int peer = FindWindowEx(parent, start, "");
        if (0 != peer)
        {
            TraverseHierarchy (parent, peer, titleless);
        }

    }
}

答案 1 :(得分:1)

使用 Microsoft Spy ++ ,您可以轻松获取已打开的任何窗口的高级信息。打开该实用程序,单击查找,然后通过将光标enter image description here从搜索框拖到所需的打开窗口,找到需要以编程方式访问的窗口。数据将显示在搜索窗口中:

enter image description here

您可以使用 Class:字段值来访问没有标题的窗口:

要按类名访问RStudio窗口,我会使用

var handle = FindWindow("Qt5QWindowIcon", null);
if (handle != IntPtr.Zero)
{
   // TO DO
}