NEWS

[C#] Thiết kế ứng dụng Single Instance và đưa ứng dụng lên trước nếu kiểm tra ứng dụng đang chạy

[C#] Thiết kế ứng dụng Single Instance và đưa ứng dụng lên trước nếu kiểm tra ứng dụng đang chạy
Đăng bởi: Thảo Meo - Lượt xem: 1627 14:14:53, 03/08/2023DEVEXPRESS   In bài viết

Xin chào các bạn, bài viết hôm nay mình hướng dẫn các bạn cách kiểm tra ứng dụng đang chạy hay chưa, và nếu ứng dụng đang chạy thì Bring to Front App, cho người dùng biết app đang chạy, không mở thêm mới một Instance App khác.

[C#] Detect App Running and Bring to Front - Single Intance App

demo_single_intance

Source code C# chỉnh ở file program.cs:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DetectAppRunning
{
    internal static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            if (CheckForAnotherInstance())
            {
                Debug.Write("Detected another instance. Close.");
                return;
            }
            Application.Run(new Form1());
        }

        

        private static bool CheckForAnotherInstance()
        {
            try
            {
                Process currentProcess = Process.GetCurrentProcess();
                foreach (Process process in Process.GetProcessesByName(currentProcess.ProcessName))
                {
                    if (process.Id != currentProcess.Id)
                    {
                        SwitchToThisWindow(process.MainWindowHandle, true);
                        Application.Exit();
                        return true;
                    }
                }
            }
            catch (Exception ex)
            {
                return false;
            }
            return false;
        }

        // Token: 0x060001C3 RID: 451
        [DllImport("user32.dll")]
        public static extern void SwitchToThisWindow(IntPtr hWnd, bool fAltTab);
    }
}

Các bạn có thể download ứng dụng về để chạy test thử.

Thanks for watching!

DOWNLOAD SOURCE

THÔNG TIN TÁC GIẢ

BÀI VIẾT LIÊN QUAN

[C#] Thiết kế ứng dụng Single Instance và đưa ứng dụng lên trước nếu kiểm tra ứng dụng đang chạy
Đăng bởi: Thảo Meo - Lượt xem: 1627 14:14:53, 03/08/2023DEVEXPRESS   In bài viết

CÁC BÀI CÙNG CHỦ ĐỀ

Đọc tiếp
.