起源
在日常辦公、游戲時,我們經常需要一些窗口處于置頂狀態,而這些窗口往往是網頁端(瀏覽器)、辦公軟件(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的效果