' ***********************************************************************
' Author : Elektro
' Last Modified On : 10-01-2014
' ***********************************************************************
' <copyright file="SetWindowPosition.vb" company="Elektro Studios">
' Copyright (c) Elektro Studios. All rights reserved.
' </copyright>
' ***********************************************************************
#Region " Example Usage "
' SetWindowPosition.SetWindowPos("proceso.exe", SetWindowPosition.Corner.BottomRight)
' SetWindowPosition.SetWindowPos("proceso.exe", X:=100, Y:=100, Bounds:=SystemInformation.VirtualScreen)
#End Region
#Region " Imports "
Imports System.ComponentModel
Imports System.Runtime.InteropServices
#End Region
''' <summary>
''' Set the position of a window.
''' </summary>
Public Class SetWindowPosition
#Region " P/Invoke "
''' <summary>
''' Platform Invocation methods (P/Invoke), access unmanaged code.
''' This class does not suppress stack walks for unmanaged code permission.
''' <see cref="System.Security.SuppressUnmanagedCodeSecurityAttribute"/> must not be applied to this class.
''' This class is for methods that can be used anywhere because a stack walk will be performed.
''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/ms182161.aspx
''' </summary>
Protected NotInheritable Class NativeMethods
#Region " Methods "
''' <summary>
''' Changes the size, position, and Z order of a child, pop-up, or top-level window.
''' These windows are ordered according to their appearance on the screen.
''' The topmost window receives the highest rank and is the first window in the Z order.
''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms633545%28v=vs.85%29.aspx
''' </summary>
''' <param name="hWnd">
''' A handle to the window.
''' </param>
''' <param name="hWndInsertAfter">
''' A special handle to the window to precede the positioned window in the Z order.
''' This parameter must be a window handle or one of the <see cref="SpecialWindowHandles"/> values.
''' </param>
''' <param name="X">
''' The new position of the left side of the window, in client coordinates.
''' </param>
''' <param name="Y">
''' The new position of the top of the window, in client coordinates.
''' </param>
''' <param name="cx">
''' The new width of the window, in pixels.
''' </param>
''' <param name="cy">
''' The new height of the window, in pixels.
''' </param>
''' <param name="uFlags">
''' The window sizing and positioning flags.
''' </param>
''' <returns><c>true</c> if the function succeeds, <c>false</c> otherwise.</returns>
<DllImport("user32.dll", SetLastError:=True)>
Friend Shared Function SetWindowPos(
ByVal hWnd As IntPtr,
ByVal hWndInsertAfter As SpecialWindowHandles,
ByVal X As Integer,
ByVal Y As Integer,
ByVal cx As Integer,
ByVal cy As Integer,
ByVal uFlags As SetWindowPosFlags
) As Boolean
End Function
''' <summary>
''' Retrieves the dimensions of the bounding rectangle of the specified window.
''' The dimensions are given in screen coordinates that are relative to the upper-left corner of the screen.
''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms633519%28v=vs.85%29.aspx
''' </summary>
''' <param name="hWnd">A handle to the window.</param>
''' <param name="rc">
''' A pointer to a RECT structure that receives the screen coordinates of
''' the upper-left and lower-right corners of the window.
''' </param>
''' <returns><c>true</c> if the function succeeds, <c>false</c> otherwise.</returns>
<DllImport("user32.dll", SetLastError:=True)>
Friend Shared Function GetWindowRect(
ByVal hWnd As IntPtr,
ByRef rc As Rectangle
) As Boolean
End Function
#End Region
#Region " Enumerations "
''' <summary>
''' Specifies the window sizing and positioning flags.
''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms633545%28v=vs.85%29.aspx
''' </summary>
<Description("Enum used as 'uFlags' parameter of 'NativeMethods.SetWindowPos' function")>
<Flags>
Friend Enum SetWindowPosFlags As UInteger
''' <summary>
''' If the calling thread and the thread that owns the window are attached to different input queues,
''' the system posts the request to the thread that owns the window.
''' This prevents the calling thread from blocking its execution while other threads process the request.
''' </summary>
''' <remarks>SWP_ASYNCWINDOWPOS</remarks>
SynchronousWindowPosition = &H4000UI
''' <summary>
''' Prevents generation of the WM_SYNCPAINT message.
''' </summary>
''' <remarks>SWP_DEFERERASE</remarks>
DeferErase = &H2000UI
''' <summary>
''' Draws a frame (defined in the window's class description) around the window.
''' </summary>
''' <remarks>SWP_DRAWFRAME</remarks>
DrawFrame = &H20UI
''' <summary>
''' Applies new frame styles set using the SetWindowLong function.
''' Sends a WM_NCCALCSIZE message to the window, even if the window's size is not being changed.
''' If this flag is not specified, WM_NCCALCSIZE is sent only when the window's size is being changed.
''' </summary>
''' <remarks>SWP_FRAMECHANGED</remarks>
FrameChanged = &H20UI
''' <summary>
''' Hides the window.
''' </summary>
''' <remarks>SWP_HIDEWINDOW</remarks>
HideWindow = &H80UI
''' <summary>
''' Does not activate the window.
''' If this flag is not set, the window is activated and moved to the top of
''' either the topmost or non-topmost group (depending on the setting of the hWndInsertAfter parameter).
''' </summary>
''' <remarks>SWP_NOACTIVATE</remarks>
DoNotActivate = &H10UI
''' <summary>
''' Discards the entire contents of the client area. If this flag is not specified,
''' the valid contents of the client area are saved and copied back into the
''' client area after the window is sized or repositioned.
''' </summary>
''' <remarks>SWP_NOCOPYBITS</remarks>
DoNotCopyBits = &H100UI
''' <summary>
''' Retains the current position (ignores X and Y parameters).
''' </summary>
''' <remarks>SWP_NOMOVE</remarks>
IgnoreMove = &H2UI
''' <summary>
''' Does not change the owner window's position in the Z order.
''' </summary>
''' <remarks>SWP_NOOWNERZORDER</remarks>
DoNotChangeOwnerZOrder = &H200UI
''' <summary>
''' Does not redraw changes.
''' If this flag is set, no repainting of any kind occurs.
''' This applies to the client area, the nonclient area (including the title bar and scroll bars),
''' and any part of the parent window uncovered as a result of the window being moved.
''' When this flag is set, the application must explicitly invalidate or
''' redraw any parts of the window and parent window that need redrawing.
''' </summary>
''' <remarks>SWP_NOREDRAW</remarks>
DoNotRedraw = &H8UI
''' <summary>
''' Same as the SWP_NOOWNERZORDER flag.
''' </summary>
''' <remarks>SWP_NOREPOSITION</remarks>
DoNotReposition = &H200UI
''' <summary>
''' Prevents the window from receiving the WM_WINDOWPOSCHANGING message.
''' </summary>
''' <remarks>SWP_NOSENDCHANGING</remarks>
DoNotSendChangingEvent = &H400UI
''' <summary>
''' Retains the current size (ignores the cx and cy parameters).
''' </summary>
''' <remarks>SWP_NOSIZE</remarks>
IgnoreResize = &H1UI
''' <summary>
''' Retains the current Z order (ignores the hWndInsertAfter parameter).
''' </summary>
''' <remarks>SWP_NOZORDER</remarks>
IgnoreZOrder = &H4UI
''' <summary>
''' Displays the window.
''' </summary>
''' <remarks>SWP_SHOWWINDOW</remarks>
ShowWindow = &H40UI
End Enum
''' <summary>
''' Specifies a special handle to the window to precede the positioned window in the Z order.
''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms633545%28v=vs.85%29.aspx
''' </summary>
<Description("Enum used as 'hWndInsertAfter' parameter of 'NativeMethods.SetWindowPos' function")>
Friend Enum SpecialWindowHandles As Integer
''' <summary>
''' Places the window at the top of the Z order.
''' </summary>
Top = 0I
''' <summary>
''' Places the window at the bottom of the Z order.
''' If the hWnd parameter identifies a topmost window,
''' the window loses its topmost status and is placed at the bottom of all other windows.
''' </summary>
Bottom = 1I
''' <summary>
''' Places the window above all non-topmost windows.
''' The window maintains its topmost position even when it is deactivated.
''' </summary>
TopMost = -1I
''' <summary>
''' Places the window above all non-topmost windows (that is, behind all topmost windows).
''' This flag has no effect if the window is already a non-topmost window.
''' </summary>
NoTopMost = -2I
End Enum
#End Region
End Class
#End Region
#Region " Enumerations "
''' <summary>
''' Specifies a screen corner.
''' </summary>
<Description("Enum used as 'Corner' parameter of 'SetWindowPos' function")>
Friend Enum Corner As Integer
''' <summary>
''' Top-Left screen corner.
''' </summary>
TopLeft = 0I
''' <summary>
''' Top-Right screen corner.
''' </summary>
TopRight = 1I
''' <summary>
''' Bottom-Left screen corner.
''' </summary>
BottomLeft = 2I
''' <summary>
''' Bottom-Right screen corner.
''' </summary>0
BottomRight = 3I
End Enum
#End Region
#Region " Public Methods "
''' <summary>
''' Set the position of a window.
''' </summary>
''' <param name="ProcessName">The process name.</param>
''' <param name="Corner">The new window position, a screen corner.</param>
''' <param name="Bounds">
''' The screen <see cref="Rectangle"/> where the window is shown.
''' If this parameter is empty, <see cref="Screen.PrimaryScreen"/> is used as default.
''' </param>
Friend Shared Sub SetWindowPos(ByVal ProcessName As String,
ByVal Corner As Corner,
Optional ByVal Bounds As Rectangle = Nothing)
Dim Rect As Rectangle ' The specified screen bounds
Dim HWND As IntPtr ' The process main window handle.
Dim Width As Integer ' The process window width.
Dim Height As Integer ' The process window height.
Dim x As Integer
Dim y As Integer
If Bounds.IsEmpty Then
Bounds = Screen.PrimaryScreen.WorkingArea
End If
' Iterate the process instances.
For Each p As Process In Process.GetProcessesByName(FixProcessName(ProcessName))
Try
' Get the main window handle.
HWND = p.MainWindowHandle
' Copy the process window position and size into the Rectangle.
' NOTE: This is not a bad practice, but 'GetWindowRect' function should use a Windows API 'RECT' structure.
NativeMethods.GetWindowRect(HWND, Rect)
Width = (Rect.Width - Rect.Left) ' Set the window width
Height = (Rect.Height - Rect.Top) ' Set the window height
Select Case Corner
Case SetWindowPosition.Corner.TopLeft
x = Bounds.Left
y = Bounds.Top
Case SetWindowPosition.Corner.TopRight
x = Bounds.Right - Width
y = Bounds.Top
Case SetWindowPosition.Corner.BottomLeft
x = Bounds.Left
y = Bounds.Bottom - Height
Case SetWindowPosition.Corner.BottomRight
x = Bounds.Right - Width
y = Bounds.Bottom - Height
End Select
' Move the Main Window.
NativeMethods.SetWindowPos(HWND, New IntPtr(NativeMethods.SpecialWindowHandles.NoTopMost),
x, y, 0, 0,
NativeMethods.SetWindowPosFlags.IgnoreResize)
Catch ex As Exception
Throw
End Try
Next
End Sub
''' <summary>
''' Set the position of a window.
''' </summary>
''' <param name="ProcessName">The process name.</param>
''' <param name="X">The new X coordinate.</param>
''' <param name="Y">The new Y coordinate.</param>
''' <param name="Bounds">
''' The screen <see cref="Rectangle"/> where the window is shown.
''' If this parameter is empty, <see cref="Screen.PrimaryScreen"/> is used as default.
''' </param>
Friend Shared Sub SetWindowPos(ByVal ProcessName As String,
ByVal X As Integer,
ByVal Y As Integer,
Optional ByVal Bounds As Rectangle = Nothing)
Dim Rect As Rectangle ' The specified screen bounds
Dim HWND As IntPtr ' The process main window handle.
Dim Width As Integer ' The process window width.
Dim Height As Integer ' The process window height.
If Bounds.IsEmpty Then
Bounds = Screen.PrimaryScreen.WorkingArea
End If
' Iterate the process instances.
For Each p As Process In Process.GetProcessesByName(FixProcessName(ProcessName))
Try
' Get the main window handle.
HWND = p.MainWindowHandle
' Copy the process window position and size into the Rectangle.
' NOTE: This is not a bad practice, but 'GetWindowRect' function should use a Windows API 'RECT' structure.
NativeMethods.GetWindowRect(HWND, Rect)
Width = (Rect.Width - Rect.Left) ' Set the window width
Height = (Rect.Height - Rect.Top) ' Set the window height
' Move the Main Window.
NativeMethods.SetWindowPos(HWND, New IntPtr(NativeMethods.SpecialWindowHandles.NoTopMost),
x, y, 0, 0,
NativeMethods.SetWindowPosFlags.IgnoreResize)
Catch ex As Exception
Throw
End Try
Next
End Sub
#End Region
#Region " Private Methods "
''' <summary>
''' Fixes the name of a process.
''' </summary>
''' <param name="name">The process name.</param>
''' <returns>System.String.</returns>
Private Shared Function FixProcessName(ByVal name As String) As String
If name.EndsWith(".exe", StringComparison.OrdinalIgnoreCase) Then
Return name.Remove(name.Length - ".exe".Length)
Else
Return name
End If
End Function
#End Region
End Class