Ottenere l'handle della finestra (hwnd), e quindi utilizzare questa funzione user32.dll: dichiarazione
VB.net:
Declare Function SetForegroundWindow Lib "user32.dll" (ByVal hwnd As Integer) As Integer
C# dichiarazione:
[DllImport("user32.dll")] public static extern int SetForegroundWindow(int hwnd)
Una considerazione è che questo non funzionerà se la finestra è ridotta a icona, quindi ho scritto il seguente metodo che gestisce anche questo caso. Ecco il codice C#, dovrebbe essere abbastanza semplice per migrare a VB.
[System.Runtime.InteropServices.DllImport("user32.dll")]
[return: System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.Bool)]
private static extern bool ShowWindow(IntPtr hWnd, ShowWindowEnum flags);
[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern int SetForegroundWindow(IntPtr hwnd);
private enum ShowWindowEnum
{
Hide = 0,
ShowNormal = 1, ShowMinimized = 2, ShowMaximized = 3,
Maximize = 3, ShowNormalNoActivate = 4, Show = 5,
Minimize = 6, ShowMinNoActivate = 7, ShowNoActivate = 8,
Restore = 9, ShowDefault = 10, ForceMinimized = 11
};
public void BringMainWindowToFront(string processName)
{
// get the process
Process bProcess = Process.GetProcessesByName(processName).FirstOrDefault();
// check if the process is running
if (bProcess != null)
{
// check if the window is hidden/minimized
if (bProcess.MainWindowHandle == IntPtr.Zero)
{
// the window is hidden so try to restore it before setting focus.
ShowWindow(bProcess.Handle, ShowWindowEnum.Restore);
}
// set user the focus to the window
SetForegroundWindow(bProcess.MainWindowHandle);
}
else
{
// the process is not running, so start it
Process.Start(processName);
}
}
Utilizzando tale codice, sarebbe più semplice impostazione delle variabili di processo adeguate e chiamando BringMainWindowToFront("processName");
Perché dichiararlo come numero intero anziché IntPtr? –
Non sembra funzionare. Puoi mostrarmi come usarlo in combinazione con il codice nella domanda originale? –
Ricevo uno zero per il valore di ritorno di SetActiveWindow, che indica un errore. Ma sto ottenendo anche 0 per GetLastWin32Error, che indica il successo. Qualche idea su dove guardare dopo? –