PDA

Click to See Complete Forum and Search --> : Center any Application From Excel


koolsid
Mar 4th, 2011, 10:12 PM
This piece of code 'Centers' an open Application Window from Excel. What I mean is that it moves the Application Window and makes it 'Center Screen' with relative to the Excel Workbook and not relative to desktop.

The following code takes an example of Notepad. To test this, open notepad and place it anywhere on the screen.

Create a new workbook and paste this code in a module and then run the Sub CenterApp()

Sid

Code Used

'~~> Code Created By Siddharth Rout on 5th March 2011
'~~> You may freely use it in your Application however
'~~> Please do not delete these 3 lines from the code

Public Declare Function FindWindow Lib "user32" Alias "FindWindowA" _
(ByVal lpClassName As String, ByVal lpWindowName As String) As Long

Public 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 Type RECT
Left As Long
Top As Long
Right As Long
Bottom As Long
End Type

Public Declare Function GetClientRect Lib "user32" (ByVal hWnd As Long, _
lpRect As RECT) As Long

Sub CenterApp()
Dim Ret As Long

'~~> Caption of Application to be centered
Dim strCaption As String

'~~> For Storing Width and Height of Application to be centered
Dim CAppWidth As Long, CAppHeight As Long

'~~> For Storing Width and Height of Excel Workbook
Dim ExcelAppWidth As Long, ExcelAppHeight As Long

'~~> This is required to get the Height and Width of
'~~> Application to be centered and of Excel Workbook
Dim rc As RECT

'~~> For new position of the Application to be centered
Dim NewLeft As Long, NewTop As Long

'~~> Testing it with Notepad. Replace this with the Application's caption
strCaption = "Untitled - Notepad"

'~~> Get the handle of the Excel - Book1. Please change the caption
'~~> accordingly. This is one classic case where WYSIWYG doesn't apply
'~~> Window will show "Book1 - Microsoft Excel" but it is the opposite
Ret = FindWindow(vbNullString, "Microsoft Excel - Book1")

'~~> Get the width and height of "Microsoft Excel - Book1"
GetClientRect Ret, rc
ExcelAppWidth = rc.Right - rc.Left
ExcelAppHeight = rc.Bottom - rc.Top

'~~> Get the width and height of Application to be centered
Ret = FindWindow(vbNullString, strCaption)
GetClientRect Ret, rc
CAppWidth = rc.Right - rc.Left
CAppHeight = rc.Bottom - rc.Top

'~~> Calculate the new position of the Application to be centered
NewLeft = (ExcelAppWidth / 2) - (CAppWidth / 2) + ActiveWindow.Left
NewTop = (ExcelAppHeight / 2) - (CAppHeight / 2) + ActiveWindow.Top

'~~> Set the position
SetWindowPos Ret, 0, NewLeft, NewTop, CAppWidth, CAppHeight, 0
End Sub

koolsid
Mar 4th, 2011, 10:29 PM
Snapshot: Before and After.