VB.NET开发:如何让表单在打开新应用时保持显示在屏幕上?
Hey there! Let's break down how to keep your VB.NET form pinned to the screen, and fix that annoying issue where it disappears when you launch apps like Microsoft Edge.
1. Basic Topmost Setup (Quick Win)
The simplest way to make your form stay on top is using the built-in TopMost property. You can set it either through the designer or directly in code:
Designer Method
- Open your form in the Visual Studio designer
- In the Properties window, find the
TopMostproperty and toggle it toTrue
Code Method
Add this line to your form's Load event handler:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load Me.TopMost = True End Sub
Note: This works for most cases, but some modern apps (like Edge) might still push your form into the background. For rock-solid persistence, we'll use a more robust approach below.
2. Force Permanent Topmost with Windows API
To guarantee your form stays visible no matter what other apps you open, we'll use the SetWindowPos Windows API function. This gives you low-level control over window z-order that bypasses basic TopMost limitations.
Add this code to your form class:
Imports System.Runtime.InteropServices Public Class Form1 ' Import the Windows API function <DllImport("user32.dll")> Private Shared Function SetWindowPos(hWnd As IntPtr, hWndInsertAfter As IntPtr, X As Integer, Y As Integer, cx As Integer, cy As Integer, uFlags As Integer) As Boolean End Function ' Constants for the API call Private Const HWND_TOPMOST As IntPtr = -1 Private Const SWP_NOMOVE As Integer = &H2 Private Const SWP_NOSIZE As Integer = &H1 Private Const SWP_SHOWWINDOW As Integer = &H40 Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load ' Lock the form to the top of the window stack SetWindowPos(Me.Handle, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE Or SWP_NOSIZE Or SWP_SHOWWINDOW) End Sub End Class
What This Does:
HWND_TOPMOST: Tells Windows to place your window above all non-topmost windows permanentlySWP_NOMOVE&SWP_NOSIZE: Keeps your form's current position and size unchangedSWP_SHOWWINDOW: Ensures the window remains visible when the API call runs
Why Your Form Disappears When Opening Edge
Microsoft Edge (and some other modern apps) sometimes launch with window attributes that can override the basic TopMost setting. The SetWindowPos API bypasses this by explicitly instructing Windows to prioritize your form's position in the window stack, no matter what other apps try to do.
Bonus: Toggle Topmost Behavior
If you want users to be able to turn the topmost setting on or off, add a button with this code:
Private Sub btnToggleTopmost_Click(sender As Object, e As EventArgs) Handles btnToggleTopmost.Click Me.TopMost = Not Me.TopMost ' If using the API, you can adjust the call to use HWND_NOTOPMOST (-2) when toggling off End Sub
内容的提问来源于stack exchange,提问作者Slayer

