这对我有用。请注意,我正在从不同的应用程序激活一个窗口,因此我无权访问 Form 对象。我也在使用 WPF 而不是 WinForms,尽管我使用的解决方案并不重要:
internal static class NativeMethods
{
public static void ActivateWindow(IntPtr windowHandle)
{
var placement = new WindowPlacement();
placement.Length = Marshal.SizeOf(placement);
GetWindowPlacement(windowHandle, ref placement);
if (placement.ShowCmd == (uint)WindowShowStyle.ShowMinimized)
{
ShowWindow(windowHandle, (uint)WindowShowStyle.Restore);
}
else
{
ShowWindow(windowHandle, placement.ShowCmd);
}
SetForegroundWindow(windowHandle);
}
private struct WindowPlacement
{
internal int Length;
internal int Flags;
internal uint ShowCmd;
internal Point MinPosition;
internal Point MaxPosition;
internal Rectangle NormalPosition;
}
private enum WindowShowStyle : uint
{
Hide = 0,
ShowNormal = 1,
ShowMinimized = 2,
ShowMaximized = 3,
Restore = 9,
}
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool GetWindowPlacement(IntPtr hWnd, ref WindowPlacement lpwndpl);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool ShowWindow(IntPtr hWnd, uint nCmdShow);
[DllImport("User32.dll")]
private static extern IntPtr SetForegroundWindow(IntPtr hWnd);
}
这就是我调用 ActivateWindow 方法的方式(减去我的日志记录代码):
private bool GiveFocusToAnotherProcess(Process runningProcess)
{
try
{
NativeMethods.ActivateWindow(runningProcess.MainWindowHandle);
}
catch (Exception ex)
{
return false;
}
return true;
}