devxlogo

Make a Form Stay on Top Redux

Make a Form Stay on Top Redux

Many routines use the SetWindowPos API to always keep a form on top. Most require the user to remember several nonintuitive arguments. I’ll not only show you how to simplify the arguments, but I’ll also illustrate the usefulness of the new Enum function. Enums have several advantages: Possible argument values are listed for you in the IDE using Microsoft’s IntelliSense, the arguments are listed in the Object Browser, and Enums are included automatically in the type library when used in a class module. This all translates into easier programming and more code reuse:

 'Paste this code into a modulePrivate 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 LongPrivate Const SWP_NOMOVE = &H2Private Const SWP_NOSIZE = &H1Private Const SWP_SHOWWINDOW = &H40Private Const SWP_NOACTIVATE = &H10Public Enum WindowPos	vbTopMost = -1&	vbNotTopMost = -2&End EnumPublic Sub SetFormPosition(hWnd As Integer, _	Position As WindowPos)	Const wFlags As Long = SWP_NOMOVE Or _		SWP_NOSIZE Or SWP_SHOWWINDOW Or _		SWP_NOACTIVATE 	If Position = vbTopMost or Position = _		vbNotTopMost Then		SetWindowPos hWnd, Position, 0, 0, 0, 0, _			wFlags	End IfEnd Sub

‘Add two command buttons to a form; then paste in ‘this code

 Private Sub Command1_Click()	'Makes form topmost	SetFormPosition Me.hWnd, vbTopMostEnd SubPrivate Sub Command2_Click()	'Restore form to normal position	SetFormPosition Me.hWnd, vbNotTopMostEnd Sub
See also  5 Tips for Working With an Onsite Interpreter
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist