
//在类中调用Windows API
[SystemRuntimeInteropServicesDllImport("user32dll", CharSet = SystemRuntimeInteropServicesCharSetAuto, ExactSpelling = true)]
public static extern IntPtr GetForegroundWindow(); //获得当前活动窗体的句柄
[SystemRuntimeInteropServicesDllImport("user32dll", EntryPoint = "SetForegroundWindow")]
public static extern bool SetForegroundWindow(IntPtr hWnd);
//调用
IntPtr handle=Handle;
if (handle!= GetForegroundWindow()) //获取当前活动窗体
SetForegroundWindow(handle); //如果不是,强制把自己的设置为活动窗体
调用可以在Timer中运行,把Timer设置一个间隔值,随便
Timer一段时间就会去检查一遍如果自己没有被顶置,那么把自己顶置
[DllImport("user32dll", EntryPoint = "FindWindow", CharSet = CharSetAuto)]
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 = IntPtrZero;
bool foundWindow = false;
int attempts = 0;
do
{
mwh = FindWindow(null, caption);
if (mwh == IntPtrZero)
{
ConsoleWriteLine("Form not yet found\n");
ThreadSleep(maxTries);
++attempts;
}
else
{
ConsoleWriteLine("Form has been found");
foundWindow = true;
}
}
while(!foundWindow && attempts<delay);
if(mwh != IntPtrZero)
return mwh;
else
throw new Exception("Coule not find Main Window");
//调用FindMainWindowHandle()方法以获取窗体句柄,例:
IntPtr wHandle= FindMainWindowHandle("窗体名",10,100);
ConsoleWriteLine("窗体句柄: " + wHandle);
以上就是关于如何获得窗口句柄与如何使窗口最前全部的内容,包括:如何获得窗口句柄与如何使窗口最前、怎样获取当前窗口句柄、等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)