设置第三方窗口置顶(SetWindowPos方法,vb.net)
起源
在日常办公、游戏时,我们经常需要一些窗口处于置顶状态,而这些窗口往往是网页端(浏览器)、办公软件(wps、office等),这些需要置顶的窗口往往自身没有明显的置顶开关,因此,想要让窗口一直处于顶端我们介绍一种有效的方法。
在自己窗体内部
Me.TopMost = True
那么我们需要在第三方窗口呢?
思路
step1
获取窗口的句柄,我们可以通过窗口的坐标来判断窗口的句柄,使用 WindowFromPoint 函数获取鼠标位置下的窗口句柄,在MouseMove事件下写入:
Private Sub Button1_MouseDown(sender As Object, e As MouseEventArgs) Handles Button1.MouseDownispick = True
End SubPrivate Sub Button1_MouseMove(sender As Object, e As MouseEventArgs) Handles Button1.MouseMoveIf ispick = True Thenhwnd = WindowFromPoint(MousePosition.X, MousePosition.Y)'GetWindowText(hwnd, s, 255)'''...End If
End Sub
Private Sub Button1_MouseUp(sender As Object, e As MouseEventArgs) Handles Button1.MouseUpispick = False'''...
End Sub<DllImport("user32.dll", EntryPoint:="WindowFromPoint")>Public Function WindowFromPoint(xPoint As Integer, yPoint As Integer) As IntPtrEnd Function
<DllImport("user32.dll", EntryPoint:="GetWindowText")>
Public Function GetWindowText(hWnd As IntPtr, lpString As StringBuilder, nMaxCount As Integer) As IntegerEnd Function
全局变量:
Dim hwnd As IntPtr
Dim ispick As Boolean
step2
编写TopMostWindow类
Public Class TopMostWindow<DllImport("user32.dll")>Public Shared Function SetWindowPos(ByVal hWnd As IntPtr,ByVal hWndInsertAfter As IntPtr,ByVal X As Integer,ByVal Y As Integer,ByVal cx As Integer,ByVal cy As Integer,ByVal uFlags As UInteger) As BooleanEnd Function' 常用常量Public Const HWND_TOPMOST = -1Public Const HWND_NOTOPMOST = -2Public Const SWP_NOSIZE As UInteger = &H1Public Const SWP_NOMOVE As UInteger = &H2Public Const SWP_SHOWWINDOW As UInteger = &H40' 设置窗口置顶Public Sub SetTopmost(ByVal targetHwnd As IntPtr)SetWindowPos(targetHwnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE Or SWP_NOSIZE Or SWP_SHOWWINDOW)End SubPublic Sub CancelTopmost(ByVal targetHwnd As IntPtr)SetWindowPos(targetHwnd, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE Or SWP_NOSIZE Or SWP_SHOWWINDOW)End Sub
End Class
来自Microsoft Learn
step3
窗口部分调用函数
Private Sub Button14_Click_1(sender As Object, e As EventArgs) Handles Button14.ClickDim t As New TopMostWindowt.SetTopmost(hwnd)
End SubPrivate Sub Button15_Click(sender As Object, e As EventArgs) Handles Button15.ClickDim t As New TopMostWindowt.CancelTopmost(hwnd)
End Sub
总结
该方法使用于几乎所有Windows窗口,使用鼠标拖拽到窗口的标题栏(非客户端区域)获取窗口句柄,设置窗口模式,效果等同于TopMost的效果