Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Force macro userform to front and focus 1

Status
Not open for further replies.

devoted

Vendor
Nov 1, 2012
23
ZA
Hi,

I have a small macro and am struggling to get it to maintain focus over the Sage 300 (2012 6.1A) application. I am just using SetForegroundWindow attached to a timer on the actual form I want at the front.

When running in the VBA editor it works ok and brings itself to the top of the editor app and gets focus when the timer fires but when running it in Accpac (just using an Accpac macro icon) it does not work. Do I need to make the Accpac VBA process active and if so then how do I go about this using VBA?

Thanks in advance.
 
You'll need to use the Windows API. I pulled this from
Code:
      Option Explicit
      Public Const SWP_NOMOVE = 2
      Public Const SWP_NOSIZE = 1
      Public Const FLAGS = SWP_NOMOVE Or SWP_NOSIZE
      Public Const HWND_TOPMOST = -1
      Public Const HWND_NOTOPMOST = -2

      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

      Public Function SetTopMostWindow(hwnd As Long, Topmost As Boolean) _
         As Long

         If Topmost = True Then 'Make the window topmost
            SetTopMostWindow = SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, 0, _
               0, FLAGS)
         Else
            SetTopMostWindow = SetWindowPos(hwnd, HWND_NOTOPMOST, 0, 0, _
               0, 0,FLAGS)
            SetTopMostWindow = False
         End If
      End Function

And use FindWindow to get the handle of your form:
Code:
Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long

Private function GetFormHandle(aForm) as long
    Dim hWnd As Long
    hWnd = FindWindow(vbNullString, aForm.Caption)
    GetFormHandle = hWnd
End Function
 
Great, thanks. I was trying SetActiveWindow and BringWindowToTop but SetWindowPos does the trick.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top