C# 激活窗口

窗體啟動(dòng)后,再次啟動(dòng)時(shí)判斷進(jìn)程是否存在,如果已經(jīng)存在則直接拉起當(dāng)前進(jìn)程,前置顯示并聚焦窗口。

/// <summary>
/// 應(yīng)用程序的主入口點(diǎn)。
/// </summary>
[STAThread]
static void Main(string[] args)
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);

    Process instance = RunningInstance();
    if (instance == null)
    {
        Application.Run(new Form1(args));
    }
    else
    {
        HandleRunningInstance(instance, args);
    }
}

private static Process RunningInstance()
{
    Process current = Process.GetCurrentProcess();
    Process[] processes = Process.GetProcessesByName(current.ProcessName);
    foreach (Process process in processes)
    {
        if (process.Id != current.Id)
        {
            if (Assembly.GetExecutingAssembly().Location.Replace("/", "\\") == current.MainModule.FileName)
            {
                return process;
            }
        }
    }
    return null;
}

private static void HandleRunningInstance(Process instance, string[] args)
{
    //ShowWindowAsync(instance.MainWindowHandle, 1); //調(diào)用api函數(shù),正常顯示窗口
    //SetForegroundWindow(instance.MainWindowHandle); //將窗口放置最前端
    IntPtr handle = FindWindow(null, WindowUtils.getWindowTitle(args[7]));
    if (handle == IntPtr.Zero)
    {
        return;
    }
    SwitchToThisWindow(handle, true);
}       
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容