设置第三方窗口置顶(SetWindowPos方法,vb.net)

起源

在日常办公、游戏时,我们经常需要一些窗口处于置顶状态,而这些窗口往往是网页端(浏览器)、办公软件(wps、office等),这些需要置顶的窗口往往自身没有明显的置顶开关,因此,想要让窗口一直处于顶端我们介绍一种有效的方法。

在自己窗体内部

Me.TopMost = True

那么我们需要在第三方窗口呢?

思路

step1 

获取窗口的句柄,我们可以通过窗口的坐标来判断窗口的句柄,使用 WindowFromPoint 函数获取鼠标位置下的窗口句柄,在MouseMove事件下写入:

Private Sub Button1_MouseDown(sender As Object, e As MouseEventArgs) Handles Button1.MouseDown
    ispick = True
End Sub

Private Sub Button1_MouseMove(sender As Object, e As MouseEventArgs) Handles Button1.MouseMove
    If ispick = True Then
        hwnd = 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.MouseUp
    ispick = False
    '''...
End Sub

 
 Public Function WindowFromPoint(xPoint As Integer, yPoint As Integer) As IntPtr

 End Function

Public Function GetWindowText(hWnd As IntPtr, lpString As StringBuilder, nMaxCount As Integer) As Integer

End Function

全局变量:

Dim hwnd As IntPtr
Dim ispick As Boolean

step2 

编写TopMostWindow类

Public Class TopMostWindow
    
    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 Boolean
    End Function

    ' 常用常量
    Public Const HWND_TOPMOST = -1
    Public Const HWND_NOTOPMOST = -2
    Public Const SWP_NOSIZE As UInteger = &H1
    Public Const SWP_NOMOVE As UInteger = &H2
    Public 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 Sub
    Public 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设置第三方窗口置顶(SetWindowPos方法,vb.net)_第1张图片

step3 

窗口部分调用函数

Private Sub Button14_Click_1(sender As Object, e As EventArgs) Handles Button14.Click
    Dim t As New TopMostWindow
    t.SetTopmost(hwnd)
End Sub

Private Sub Button15_Click(sender As Object, e As EventArgs) Handles Button15.Click
    Dim t As New TopMostWindow
    t.CancelTopmost(hwnd)
End Sub

总结

该方法使用于几乎所有Windows窗口,使用鼠标拖拽到窗口的标题栏(非客户端区域)获取窗口句柄,设置窗口模式,效果等同于TopMost的效果

你可能感兴趣的:(vb.net,窗体活动,调用,.net,vb.net,窗口,置顶)