1
我從類庫打開WPF窗口。如何從類庫中檢查WPF窗口是否已經打開?到System.Windows.Application.Current.Windows
任何引用產生此錯誤:如何從類庫檢查WPF窗口是否打開
Object reference not set to an instance of an object
注:我從一個WPF項目,我改變了輸出類型類庫創建的類庫。
我從類庫打開WPF窗口。如何從類庫中檢查WPF窗口是否已經打開?到System.Windows.Application.Current.Windows
任何引用產生此錯誤:如何從類庫檢查WPF窗口是否打開
Object reference not set to an instance of an object
注:我從一個WPF項目,我改變了輸出類型類庫創建的類庫。
我試圖引用System.Windows但無法這樣做。
但是強制執行一個只有一個進程實例正在運行的規則是一個有趣的任務。在Win32上還有很多其他的編碼算法。它會檢測您的應用程序是否已經運行。如果檢測到,它會將該應用程序放到前臺(如果它被最小化)。
using System.Diagnostics;
using System.Runtime.InteropServices;
public class OnlyOneWindow
{
[DllImport("user32.dll")] private static extern
bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")] private static extern
bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);
[DllImport("user32.dll")] private static extern
bool IsIconic(IntPtr hWnd);
private const int SW_HIDE = 0;
private const int SW_SHOWNORMAL = 1;
private const int SW_SHOWMINIMIZED = 2;
private const int SW_SHOWMAXIMIZED = 3;
private const int SW_SHOWNOACTIVATE = 4;
private const int SW_RESTORE = 9;
private const int SW_SHOWDEFAULT = 10;
public OnlyOneWindow()
{
// get the name of our process
string proc=Process.GetCurrentProcess().ProcessName;
// get the list of all processes by that name
Process[] processes=Process.GetProcessesByName(proc);
// if there is more than one process...
if (processes.Length > 1)
{
// Assume there is our process, which we will terminate,
// and the other process, which we want to bring to the
// foreground. This assumes there are only two processes
// in the processes array, and we need to find out which
// one is NOT us.
// get our process
Process p=Process.GetCurrentProcess();
int n=0; // assume the other process is at index 0
// if this process id is OUR process ID...
if (processes[0].Id==p.Id)
{
// then the other process is at index 1
n=1;
}
// get the window handle
IntPtr hWnd=processes[n].MainWindowHandle;
// if iconic, we need to restore the window
if (IsIconic(hWnd))
{
ShowWindowAsync(hWnd, SW_RESTORE);
}
// bring it to the foreground
SetForegroundWindow(hWnd);
// exit our process
return;
}
// ... continue with your application initialization here.
}
}
窗口是否在同一個過程中?如果你只想顯示窗口的一個實例,你有沒有考慮過把它變成單例? – vesan
我沒有看單身人士,並會這樣做。感謝您的建議。我也改變了我的設計,使我不需要使用WPF窗口,而是使用WinForm。我沒有任何麻煩檢查winform的實例。 – GlxyM31