![]() |
[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ử.
Theo LapTrinhVB.Net
no comment sexy tks!
Trả lờiXóadie link?
Trả lờiXóa