我有以下情況: WinForms應用程序只允許運行此應用程序的一個實例(此處使用互斥鎖來檢查)。從一些paramatere開始的應用程序是runnig,但隱藏。當有人再次點擊應用程序時,Mutex會檢測到該應用程序已在運行,並通過本地方法調用「取消隱藏」主窗體(請參見下面的方法BringWindowToFront)。使用PInvoke顯示錶格
這裏是找到並顯示窗體窗口代碼:
public static class NativeMethods
{
public enum ShowWindowOptions
{
FORCEMINIMIZE = 11,
HIDE = 0,
MAXIMIZE = 3,
MINIMIZE = 6,
RESTORE = 9,
SHOW = 5,
SHOWDEFAULT = 10,
SHOWMAXIMIZED = 3,
SHOWMINIMIZED = 2,
SHOWMINNOACTIVE = 7,
SHOWNA = 8,
SHOWNOACTIVATE = 4,
SHOWNORMAL = 1
}
[DllImport("user32.dll")]
public static extern int ShowWindow(int hwnd, int cmdShow);
[DllImport("USER32.DLL", CharSet = CharSet.Unicode)]
public static extern IntPtr FindWindow(String lpClassName, String lpWindowName);
[DllImport("USER32.DLL")]
public static extern bool SetForegroundWindow(IntPtr hWnd);
public static void BringWindowToFront(string windowTitle)
{
// Get a handle to the application.
IntPtr handle = FindWindow(null, windowTitle);
// Verify that app is a running process.
if (handle == IntPtr.Zero)
{
return;
}
// With this line you have changed window status from example, minimized to normal
ShowWindow((int)handle, (int)ShowWindowOptions.SHOWDEFAULT);
// Make app the foreground application
SetForegroundWindow(handle);
}
}
一切都很好,但我需要一個功能呢。 我想在主窗體第一次取消隱藏時再顯示另一個窗體。通常我會通過表格_Shown事件。但是當我使用PInvoke方法來顯示窗口時,這個事件不會被激活。
所以基本上我想顯示其他形式時,將顯示主窗體(使用的ShowWindow PInvoke的方法)
這可能嗎?任何其他想法如何實現它?
預先感謝您。
你是否堅持P/Invoke mec hanism爲了做到這一點?還有其他方法可以完全在C#代碼中生成單個實例應用程序。 – ChrisF 2010-07-13 20:18:25
我通過Mutex實現了單例。現在我堅持要顯示額外的窗體後,我顯示主窗口由公共靜態extern int ShowWindow(int hwnd,int cmdShow); – binball 2010-07-13 20:53:07