勇哥注:
在下面的winfrom中,调用了netMarketing类库的appContainer容器控件把记事本程序嵌入进来。
(appContainer容器控件见 http://www.skcircle.com/?id=1930 )
这个时候,我们如何得到这个记事本编辑区的窗体句柄呢?

通过Spy++分析,这个窗体的全部子窗体层级构造如下图所示:
(句柄为 0040B84的窗体就是程序主窗体)
从中我们发现一个知识,就是原来所有的按钮、文本框、Lable 等等控件全部都是窗体。

直接上代码,见下面的调用类源码。
调用方式为:
FindWindow fw = new FindWindow(IntPtr.Zero, "Notepad", "无标题 - 记事本", 10);
其实,这个并没有实现Spy++那种效果。
勇哥实验过,传入IntPtr.Zero从顶层窗口找起,是可以找到的。
但是,如果从当前窗口找起,又找不到。
暂时不明白为什么。
另外,其实如果有多个记事本的话,它的窗体类名与窗口标题都是一样的,这样该怎么找?
本着用到的时候再研究的原则,留待以后吧。
调用类源码:
class FindWindow
{
[DllImport("user32")]
[return: MarshalAs(UnmanagedType.Bool)]
//IMPORTANT : LPARAM must be a pointer (InterPtr) in VS2005, otherwise an exception will be thrown
private static extern bool EnumChildWindows(IntPtr window, EnumWindowProc callback, IntPtr i);
//the callback function for the EnumChildWindows
private delegate bool EnumWindowProc(IntPtr hWnd, IntPtr parameter);
//if found return the handle , otherwise return IntPtr.Zero
[DllImport("user32.dll", EntryPoint = "FindWindowEx")]
private static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
private string m_classname; // class name to look for
private string m_caption; // caption name to look for
private DateTime start;
private int m_timeout;//If exceed the time. Indicate no windows found.
private IntPtr m_hWnd; // HWND if found
public IntPtr FoundHandle
{
get { return m_hWnd; }
}
private bool m_IsTimeOut;
public bool IsTimeOut
{
get { return m_IsTimeOut; }
set { m_IsTimeOut = value; }
}
// ctor does the work--just instantiate and go
public FindWindow(IntPtr hwndParent, string classname, string caption, int timeout)
{
m_hWnd = IntPtr.Zero;
m_classname = classname;
m_caption = caption;
m_timeout = timeout;
start = DateTime.Now;
FindChildClassHwnd(hwndParent, IntPtr.Zero);
}
/// <summary>
/// Find the child window, if found m_classname will be assigned
/// </summary>
/// <param name="hwndParent">parent's handle</param>
/// <param name="lParam">the application value, nonuse</param>
/// <returns>found or not found</returns>
private bool FindChildClassHwnd(IntPtr hwndParent, IntPtr lParam)
{
EnumWindowProc childProc = new EnumWindowProc(FindChildClassHwnd);
IntPtr hwnd = FindWindowEx(hwndParent, IntPtr.Zero, m_classname, m_caption);
if (hwnd != IntPtr.Zero)
{
this.m_hWnd = hwnd; // found: save it
m_IsTimeOut = false;
return false; // stop enumerating
}
DateTime end = DateTime.Now;
if (start.AddSeconds(m_timeout) < end)
{
m_IsTimeOut = true;
return false;
}
EnumChildWindows(hwndParent, childProc, IntPtr.Zero); // recurse redo FindChildClassHwnd
return true;// keep looking
}
}本文参考了下面的贴子:
http://t.zoukankan.com/ArRan-p-2818170.html
---------------------
作者:hackpig
来源:www.skcircle.com
版权声明:本文为博主原创文章,转载请附上博文链接!


少有人走的路


















