Home > Software design >  How to maximize and set focus to foreground of the opened outlook email message?
How to maximize and set focus to foreground of the opened outlook email message?

Time:04-24

I am using below code to open an email item (with specific conditions).
I need after that to maximize the opened outlook email window and set focus for it to be foreground.

Option Explicit
Option Compare Text
Public WithEvents MyItem As Outlook.MailItem
Public EventsDisable As Boolean
Private Sub Application_ItemLoad(ByVal Item As Object)
    If EventsDisable = True Then Exit Sub
    If Item.Class = olMail Then
        Set MyItem = Item
    End If
End Sub
Private Sub myItem_Open(Cancel As Boolean)
    EventsDisable = True
        If MyItem.Subject = "Auto Plan" And Application.ActiveExplorer.CurrentFolder.Name = "MyTemplate" Then
   'Code to maximize the opened outlook email window and set focus for it to be foreground
        End If
    EventsDisable = False
End Sub

the following Windows API function

#If Win64 Then
    Private Declare PtrSafe Function SetForegroundWindow Lib "user32" _
               (ByVal hWnd As LongPtr) As LongPtr
#Else
    Private Declare Function SetForegroundWindow Lib "user32" _
               (ByVal hWnd As Long) As Long
#End If

Public Sub Bring_to_front()
    Dim setFocus As Long
    setFocus = SetForegroundWindow(xxxxxxx.hWnd)
End Sub

thanks for any useful comments and answer.

CodePudding user response:

Call MailItem.Display, then activate the Inspector object by calling Inspector.Activate. Inspector object can be retrieved from MailItem.GetInspector.

One thing to keep in mind is that Windows will not bring a window to the foreground if the parent process is not in the foreground. You would need to use AttachThreadInput function for that - see https://stackoverflow.com/a/17793132/332059

CodePudding user response:

You can use the SetForegroundWindow method which brings the thread that created the specified window into the foreground and activates the window. Keyboard input is directed to the window, and various visual cues are changed for the user. Alternatively you may consider using the Activate method of the Explorer or Inspector classes from the Outlook object model.

To maximize the window you could use the ShowWindow method from Windows API, here is a possible declaration in VBA:

Public Declare Function ShowWindow Lib "user32" _
  (ByVal hwnd As Long, ByVal nCmdSHow As Long) As Long

private SW_MAXIMIZE as Long = 3;
private SW_MINIMIZE as Long = 6;

So, you need to pass a window handle and the SW_MAXIMIZE value as the second parameter to maximize the window. See How to minimize/maximize opened Applications for more information.

  • Related