Obtener el identificador de ventana (hWnd), y luego utilizar esta función user32.dll: declaración
VB.net:
Declare Function SetForegroundWindow Lib "user32.dll" (ByVal hwnd As Integer) As Integer
C# declaración:
[DllImport("user32.dll")] public static extern int SetForegroundWindow(int hwnd)
Una consideración es que esto no funcionará si la ventana está minimizada, entonces he escrito el siguiente método que también maneja este caso. Aquí está el código C#, debería ser bastante sencillo migrar esto 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);
}
}
El uso de ese código, sería tan simple como el establecimiento de las variables de proceso adecuadas y llamando BringMainWindowToFront("processName");
¿Por qué se declaran como entero en lugar de IntPtr? –
Parece que no funciona. ¿Puede mostrarme cómo usarlo junto con el código en la pregunta original? –
Obtengo un cero para el valor de retorno de SetActiveWindow, que indica un error. Pero también obtengo 0 para GetLastWin32Error, lo que indica éxito. ¿Alguna idea de dónde mirar después? –