From 2b40e87eb90c072cfe5895474bb45da3f6b20237 Mon Sep 17 00:00:00 2001 From: 2dust <31833384+2dust@users.noreply.github.com> Date: Fri, 1 Jul 2022 20:50:47 +0800 Subject: [PATCH] read handle from reg and show the window --- v2rayN/v2rayN/Forms/MainForm.cs | 6 ++++++ v2rayN/v2rayN/Program.cs | 23 +++++++++++++++++------ v2rayN/v2rayN/Tool/Utils.cs | 26 ++++++++++++++++++++++++++ 3 files changed, 49 insertions(+), 6 deletions(-) diff --git a/v2rayN/v2rayN/Forms/MainForm.cs b/v2rayN/v2rayN/Forms/MainForm.cs index 39b3a072..eb7d337d 100644 --- a/v2rayN/v2rayN/Forms/MainForm.cs +++ b/v2rayN/v2rayN/Forms/MainForm.cs @@ -1138,6 +1138,12 @@ namespace v2rayN.Forms ShowInTaskbar = false; SetVisibleCore(false); + + //write Handle to reg + if (IsHandleCreated) + { + Utils.RegWriteValue(Global.MyRegPath, Utils.WindowHwndKey, Convert.ToString((long)Handle)); + } } #endregion diff --git a/v2rayN/v2rayN/Program.cs b/v2rayN/v2rayN/Program.cs index 8a3e27db..a8154406 100644 --- a/v2rayN/v2rayN/Program.cs +++ b/v2rayN/v2rayN/Program.cs @@ -1,18 +1,13 @@ using System; -using System.Diagnostics; using System.Threading; using System.Windows.Forms; using v2rayN.Forms; -using v2rayN.Properties; using v2rayN.Tool; namespace v2rayN { static class Program { - [System.Runtime.InteropServices.DllImport("user32.dll")] - private static extern bool SetProcessDPIAware(); - /// /// 应用程序的主入口点。 /// @@ -21,7 +16,7 @@ namespace v2rayN { if (Environment.OSVersion.Version.Major >= 6) { - SetProcessDPIAware(); + Utils.SetProcessDPIAware(); } Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); @@ -47,6 +42,22 @@ namespace v2rayN } else { + try + { + //read handle from reg and show the window + long.TryParse(Utils.RegReadValue(Global.MyRegPath, Utils.WindowHwndKey, ""), out long llong); + if (llong > 0) + { + var hwnd = (IntPtr)llong; + if (Utils.IsWindow(hwnd)) + { + Utils.ShowWindow(hwnd, 4); + Utils.SwitchToThisWindow(hwnd, true); + return; + } + } + } + catch { } UI.ShowWarning($"v2rayN is already running(v2rayN已经运行)"); } } diff --git a/v2rayN/v2rayN/Tool/Utils.cs b/v2rayN/v2rayN/Tool/Utils.cs index b07c5929..54f65f35 100644 --- a/v2rayN/v2rayN/Tool/Utils.cs +++ b/v2rayN/v2rayN/Tool/Utils.cs @@ -24,6 +24,7 @@ using System.Web; using log4net; using System.Linq; using System.Security.Cryptography; +using System.Runtime.InteropServices; namespace v2rayN { @@ -1111,5 +1112,30 @@ namespace v2rayN #endregion + + #region Windows API + + public static string WindowHwndKey + { + get + { + return $"WindowHwnd_{GetMD5(StartupPath())}"; + } + } + + [DllImport("user32.dll")] + public static extern bool SetProcessDPIAware(); + + [DllImport("user32.dll")] + public static extern int ShowWindow(IntPtr hwnd, int nCmdShow); + + [DllImport("user32.dll")] + public static extern int SwitchToThisWindow(IntPtr hwnd, bool fUnknown); + + [DllImport("user32.dll")] + public static extern bool IsWindow(IntPtr hwnd); + + + #endregion } }