讓VB最上層顯示

「最上層顯示」也是一個很不錯的功能,能讓使用者一邊使用其它程式一邊使用你寫的VB程式

那麼該怎麼做才能讓VB表單最上層顯示呢?

這時就要宣告API啦!

如何宣告API?   請參考這篇

但我們這回要宣告的是”SetWindowPos”,不是”ShellExecute”

以下是Private宣告SetWindowPos的程式碼:

Private Declare Function SetWindowPos Lib “user32” Alias “SetWindowPos” (ByVal hwnd As Long, ByVal hWndInsertAfter As Long, ByVal x As Long, ByVal y As Long, ByVal cx As Long, ByVal cy As Long, ByVal wFlags As Long) As Long

將上面程式碼貼到你想要最上層顯示的表單上

然後再新增一個按鈕(Command1) Caption = “最上層顯示”

然後在Private Sub Command1_Click()再宣告一個變數X→(Dim X),來記錄按下按鈕的動作

而Private Sub Command1_Click()程式撰寫如下:

Private Sub Command1_Click()
If X = 0 Then    ‘只宣告X變數預設值是0,第一次按下按鈕時X為0
IntR = SetWindowPos(Me.hwnd, -1, 0, 0, 0, 0, 3)   ‘最上層顯示
X = X + 1      ‘記錄已按過一次按鈕
Command1.Caption = “取消最上層顯示”
ElseIf X = 1 Then    ‘第二次按按鈕
IntR = SetWindowPos(Me.hwnd, -2, 0, 0, 0, 0, 3)   ‘取消最上層顯示
X = 0   ‘將X變回0
Command1.Caption = “最上層顯示”
End If
End Sub

綜合以上程式碼,應寫出:

Private Declare Function SetWindowPos Lib “user32” (ByVal hwnd As Long, ByVal hWndInsertAfter As Long, ByVal X As Long, ByVal y As Long, ByVal cx As Long, ByVal cy As Long, ByVal wFlags As Long) As Long
Dim X
Private Sub Command1_Click()
If X = 0 Then    ‘只宣告X變數預設值是0,第一次按下按鈕時X為0
IntR = SetWindowPos(Me.hwnd, -1, 0, 0, 0, 0, 3)   ‘最上層顯示
X = X + 1      ‘記錄已按過一次按鈕
Command1.Caption = “取消最上層顯示”
ElseIf X = 1 Then    ‘第二次按按鈕
IntR = SetWindowPos(Me.hwnd, -2, 0, 0, 0, 0, 3)   ‘取消最上層顯示
X = 0   ‘將X變回0
Command1.Caption = “最上層顯示”
End If
End Sub

執行結果如下圖:

剛開始執行

第一次按下按鈕

看看是否有最上層顯示

這樣就OK啦!

.

核取式最上層顯示

上面所講的是利用按鈕來進行最上層顯示的控制

現在我要教「用核取式方塊」來做控制

首先,在表單佈置一個Check1和Label1

Label1的Caption設定成”最上層顯示”

然後利用上面的方法宣告SetWindowPos

接下來撰寫Private Sub Check1_Click()程式碼,如下:

Private Sub Check1_Click()

If Check1.Value = 1 Then  ‘若按下Check1後,Value的值變成1
IntR = SetWindowPos(Me.hwnd, -1, 0, 0, 0, 0, 3)   ‘最上層顯示
ElseIf Check1.Value = 0 Then    ‘若按下Check1後,Value的值變成0
IntR = SetWindowPos(Me.hwnd, -2, 0, 0, 0, 0, 3)    ‘取消最上層顯示
End If

End Sub

若您的程式照以上方法還是不能最上層顯示的話

再在Private Sub Form_Resize()中撰寫下列程式碼:

Private Sub Form_Resize()
If Check1.Value = 1 Then
IntR = SetWindowPos(Me.hwnd, -1, 0, 0, 0, 0, 3)
ElseIf Check1.Value = 0 Then
IntR = SetWindowPos(Me.hwnd, -2, 0, 0, 0, 0, 3)
End If
End Sub

綜合以上程式碼,所寫出來的程式應為:

Private Declare Function SetWindowPos Lib “user32” (ByVal hwnd As Long, ByVal hWndInsertAfter As Long, ByVal X As Long, ByVal Y As Long, ByVal cx As Long, ByVal cy As Long, ByVal wFlags As Long) As Long

Private Sub Check1_Click()
If Check1.Value = 1 Then
IntR = SetWindowPos(Me.hwnd, -1, 0, 0, 0, 0, 3)
ElseIf Check1.Value = 0 Then
IntR = SetWindowPos(Me.hwnd, -2, 0, 0, 0, 0, 3)
End If
End Sub

Private Sub Form_Resize()
If Check1.Value = 1 Then
IntR = SetWindowPos(Me.hwnd, -1, 0, 0, 0, 0, 3)
ElseIf Check1.Value = 0 Then
IntR = SetWindowPos(Me.hwnd, -2, 0, 0, 0, 0, 3)
End If
End Sub

.

本篇教學到此結束

文章分類:VB6.0|標籤:,

迴響已關閉