我試圖啓動一個應用程序,並將其帶到前面。 但是,應用程序啓動正常,然後結束了 啓動應用程序。 請注意,在已運行的最小化應用程序上使用類似的方法可以正常工作(爲簡潔起見,此代碼已從此示例中刪除) - 它只在啓動應用程序的新實例時失敗。 任何想法?由於SetForegroundWindow不工作
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
namespace Launcher
{
class Program
{
[DllImport("User32.dll", SetLastError = true)]
private static extern int SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern Boolean ShowWindow(IntPtr hWnd, Int32 nCmdShow);
[DllImport("user32.dll")]
private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);
private const int SW_SHOWMAXIMIZED = 3;
private static readonly IntPtr HWND_TOP = new IntPtr(0);
private const UInt32 SWP_NOSIZE = 0x0001;
private const UInt32 SWP_NOMOVE = 0x0002;
private const UInt32 SWP_SHOWWINDOW = 0x0040;
static void Main(string[] args)
{
string wd = @"C:\Program Files (x86)\MyFolder";
string fn = "MyApplication.exe";
if (!System.IO.File.Exists(wd + @"\" + fn)) return;
Process p = new Process();
p.StartInfo.WorkingDirectory = wd;
p.StartInfo.FileName = fn;
p.StartInfo.CreateNoWindow = false;
p.Start(); // app launches OK
Thread.Sleep(5000);
SetForegroundWindow(p.MainWindowHandle); // this has no effect
SetWindowPos(p.MainWindowHandle, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW);
}
}
}
}
「MyApplication.exe」是一種什麼樣的應用程序? –
有關SetForegroundWindow何時運行的規則有很多。請參閱其文檔的註釋:http://msdn.microsoft.com/en-us/library/windows/desktop/ms633539(v=vs.85).aspx – shf301
@Erik:MyApplication.exe是任何Windows窗體應用程序。 – radders