我写了一个类如何在类中获取窗口句柄( form1窗体) 不是很懂能不能写详细点 .......
3个回答
2011-08-29
展开全部
[DllImport("user32.dll", EntryPoint = "FindWindow", CharSet = CharSet.Auto)]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
/// <summary>
/// 获取有名字窗体句柄
/// </summary>
/// <param name="caption">窗体名</param>
/// <param name="delay">循环查询次数</param>
/// <param name="maxTries">停顿时间</param>
/// <returns>句柄 IntPtr</returns>
static IntPtr FindMainWindowHandle(String caption,int delay,int maxTries)
{
IntPtr mwh = IntPtr.Zero;
bool foundWindow = false;
int attempts = 0;
do
{
mwh = FindWindow(null, caption);
if (mwh == IntPtr.Zero)
{
Console.WriteLine("Form not yet found\n");
Thread.Sleep(maxTries);
++attempts;
}
else
{
Console.WriteLine("Form has been found");
foundWindow = true;
}
}
while(!foundWindow && attempts<delay);
if(mwh != IntPtr.Zero)
return mwh;
else
throw new Exception("Coule not find Main Window");
//调用FindMainWindowHandle()方法以获取窗体句柄,例:
IntPtr wHandle= FindMainWindowHandle("窗体名",10,100);
Console.WriteLine("窗体句柄: " + wHandle);
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
/// <summary>
/// 获取有名字窗体句柄
/// </summary>
/// <param name="caption">窗体名</param>
/// <param name="delay">循环查询次数</param>
/// <param name="maxTries">停顿时间</param>
/// <returns>句柄 IntPtr</returns>
static IntPtr FindMainWindowHandle(String caption,int delay,int maxTries)
{
IntPtr mwh = IntPtr.Zero;
bool foundWindow = false;
int attempts = 0;
do
{
mwh = FindWindow(null, caption);
if (mwh == IntPtr.Zero)
{
Console.WriteLine("Form not yet found\n");
Thread.Sleep(maxTries);
++attempts;
}
else
{
Console.WriteLine("Form has been found");
foundWindow = true;
}
}
while(!foundWindow && attempts<delay);
if(mwh != IntPtr.Zero)
return mwh;
else
throw new Exception("Coule not find Main Window");
//调用FindMainWindowHandle()方法以获取窗体句柄,例:
IntPtr wHandle= FindMainWindowHandle("窗体名",10,100);
Console.WriteLine("窗体句柄: " + wHandle);
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询