C# codeusing System;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;
namespace Class1
{
/// <summary>
/// WinAPI 的摘要说明。
/// </summary>
public class SetWindow
{
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
private static extern IntPtr GetForegroundWindow(); //WINAPI 获取当前活动窗体的句柄
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
private static extern bool SetForegroundWindow(IntPtr hWnd); //WINAPI 设置当前活动窗体的句柄
private Thread Th;
private IntPtr MainInt;
public SetWindow(IntPtr MainIntPrt)
{
MainInt=MainIntPrt;
}
/// <summary>
/// 开始线程
/// </summary>
public void Star()
{
Th=new Thread(new ThreadStart(SetForm));
Th.Start();
}
private void SetForm()
{
while(true)
{
if(MainInt!=GetForegroundWindow())SetForegroundWindow(MainInt);
Thread.Sleep(1);
}
}
/// <summary>
/// 关闭线程
/// </summary>
public void Close()
{
Th.Abort();
}
}
}
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;
namespace Class1
{
/// <summary>
/// WinAPI 的摘要说明。
/// </summary>
public class SetWindow
{
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
private static extern IntPtr GetForegroundWindow(); //WINAPI 获取当前活动窗体的句柄
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
private static extern bool SetForegroundWindow(IntPtr hWnd); //WINAPI 设置当前活动窗体的句柄
private Thread Th;
private IntPtr MainInt;
public SetWindow(IntPtr MainIntPrt)
{
MainInt=MainIntPrt;
}
/// <summary>
/// 开始线程
/// </summary>
public void Star()
{
Th=new Thread(new ThreadStart(SetForm));
Th.Start();
}
private void SetForm()
{
while(true)
{
if(MainInt!=GetForegroundWindow())SetForegroundWindow(MainInt);
Thread.Sleep(1);
}
}
/// <summary>
/// 关闭线程
/// </summary>
public void Close()
{
Th.Abort();
}
}
}
调用:
SetWin =new Class1.SetWindow(this.Handle);
SetWin.Star();
本文介绍了一种使用C#实现窗体始终置顶的技术方案。通过调用WinAPI函数,结合线程循环检查,确保指定窗体始终保持在最前端显示。此技术适用于需要长期关注特定应用界面的场景。
900

被折叠的 条评论
为什么被折叠?



