【问题标题】:Get handle of a specific window using user32.dll使用 user32.dll 获取特定窗口的句柄
【发布时间】:2011-08-08 10:45:51
【问题描述】:

如何使用 user32.dll 获取特定窗口的句柄?

谁能给我一个简短的例子?

【问题讨论】:

    标签: c#


    【解决方案1】:

    尝试以下方法:

    // For Windows Mobile, replace user32.dll with coredll.dll
    [DllImport("user32.dll", SetLastError = true)]
    static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
    
    // Find window by Caption only. Note you must pass IntPtr.Zero as the first parameter.
    
    [DllImport("user32.dll", EntryPoint="FindWindow", SetLastError = true)]
    static extern IntPtr FindWindowByCaption(IntPtr ZeroOnly, string lpWindowName);
    
    // You can also call FindWindow(default(string), lpWindowName) or FindWindow((string)null, lpWindowName)
    

    您可以按如下方式使用这些声明

    // Find window by Caption
    public static IntPtr FindWindow(string windowName)
    {
        var hWnd = FindWindow(windowName, null); 
        return hWnd;
    }
    

    这是代码的简洁版本:

    public class WindowFinder
    {
        // For Windows Mobile, replace user32.dll with coredll.dll
        [DllImport("user32.dll", SetLastError = true)]
        static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
        
        public static IntPtr FindWindow(string caption)
        {
            return FindWindow(String.Empty, caption);
        }
    }
    

    【讨论】:

    • 我如何从主要访问这些方法?
    • 我把这个方法称为:例如 FindWindow("notepad")?
    • 我怎么知道处理程序被激活了?谢谢
    • 如何获取 windowText 和 className?因为目前我没有这个元素。
    • 我不得不使用FindWindow(null, caption); 而不是FindWindow(String.Empty, caption);
    猜你喜欢
    • 2012-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-28
    • 2012-11-22
    • 2011-02-26
    • 1970-01-01
    • 2014-01-28
    相关资源
    最近更新 更多