20 August, 2023

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

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

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);
    }
}

Và code C# sau khi mình chuyển đổi sang Visual Basic
Imports System
Imports System.Collections.Generic
Imports System.Diagnostics
Imports System.Linq
Imports System.Runtime.InteropServices
Imports System.Threading.Tasks
Imports System.Windows.Forms

Namespace DetectAppRunning
    Friend Module Program
        <STAThread>
        Private Sub Main()
            Application.EnableVisualStyles()
            Application.SetCompatibleTextRenderingDefault(False)

            If CheckForAnotherInstance() Then
                Debug.Write("Detected another instance. Close.")
                Return
            End If

            Application.Run(New Form1())
        End Sub

        Private Function CheckForAnotherInstance() As Boolean
            Try
                Dim currentProcess As Process = Process.GetCurrentProcess()

                For Each process As Process In Process.GetProcessesByName(currentProcess.ProcessName)

                    If process.Id <> currentProcess.Id Then
                        SwitchToThisWindow(process.MainWindowHandle, True)
                        Application.[Exit]()
                        Return True
                    End If
                Next

            Catch ex As Exception
                Return False
            End Try

            Return False
        End Function

        <DllImport("user32.dll")>
        Sub SwitchToThisWindow(ByVal hWnd As IntPtr, ByVal fAltTab As Boolean)
    End Module
End Namespace

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

Theo LapTrinhVB.Net
All Right Reserved © 2015 By Hung Pro VN
Hung.Pro.VN Sharing Your Own Knowledge and Creative Thinking Every Day and Many Other Things.