Skip to content

Commit

Permalink
Fix global/zh server detection
Browse files Browse the repository at this point in the history
  • Loading branch information
Kxnrl committed May 3, 2023
1 parent 5081f41 commit 5cfb6e5
Show file tree
Hide file tree
Showing 4 changed files with 168 additions and 51 deletions.
137 changes: 88 additions & 49 deletions src/Program.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
using DiscordRPC;
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Management;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
Expand Down Expand Up @@ -46,10 +49,8 @@ static void Main()

Debug.Print($"InLoop");

var hndlZh = FindWindow("UnityWndClass", "崩坏:星穹铁道");
var hndlEn = FindWindow("UnityWndClass", "Honkai: Star Rail");
if (hndlZh == IntPtr.Zero &&
hndlEn == IntPtr.Zero)
var handle = FindWindow("UnityWndClass", "崩坏:星穹铁道"); // "Honkai: Star Rail"
if (handle == IntPtr.Zero)
{
Debug.Print($"Not found game process.");
playing = false;
Expand All @@ -66,69 +67,37 @@ static void Main()

try
{
var procEn = Process.GetProcesses().FirstOrDefault(x => x.MainWindowHandle == hndlEn);
var procZh = Process.GetProcesses().FirstOrDefault(x => x.MainWindowHandle == hndlZh);
var process = Process.GetProcesses().First(x => x.MainWindowHandle == handle);

Debug.Print($"Check process with {hndlZh} | {procZh?.ProcessName} || {hndlEn} | {procEn?.ProcessName}");
var isGlobal = CheckGlobal(process);

if (procZh != null)
Debug.Print($"Check process with {handle} | {process.ProcessName}");

if (!isGlobal)
{
if (!playing)
{
playing = true;

clientZh.SetPresence(new RichPresence
{
Assets = new Assets
{
LargeImageKey = "logo",
LargeImageText = "崩坏:星穹铁道",
},
Timestamps = Timestamps.Now,
});

Debug.Print($"Set RichPresence to {procZh?.ProcessName}");
clientZh.UpdateRpc("logo", "崩坏:星穹铁道");
Debug.Print($"Set RichPresence to {process.ProcessName}");
}
else
{
Debug.Print($"Keep RichPresence to {procZh?.ProcessName}");
Debug.Print($"Keep RichPresence to {process.ProcessName}");
}
}
else if (procEn != null)
else
{
if (!playing)
{
playing = true;

clientEn.SetPresence(new RichPresence
{
Assets = new Assets
{
LargeImageKey = "logo",
LargeImageText = "Honkai: Star Rail",
},
Timestamps = Timestamps.Now,
});

Debug.Print($"Set RichPresence to {procEn?.ProcessName}");
clientEn.UpdateRpc("logo", "Honkai: Star Rail");
Debug.Print($"Set RichPresence to {process.ProcessName}");
}
else
{
Debug.Print($"Keep RichPresence to {procEn?.ProcessName}");
}
}
else
{
playing = false;
if (clientEn.CurrentPresence != null)
{
clientEn.ClearPresence();
}
if (clientZh.CurrentPresence != null)
{
clientZh.ClearPresence();
Debug.Print($"Keep RichPresence to {process.ProcessName}");
}
Debug.Print($"Clear RichPresence");
}
}
catch (Exception e)
Expand Down Expand Up @@ -192,6 +161,76 @@ static void Main()
Application.Run();
}

[DllImport("user32.dll", EntryPoint = "FindWindow")]
private static void UpdateRpc(this DiscordRpcClient client, string key, string text)
=> client.SetPresence(new RichPresence
{
Assets = new Assets
{
LargeImageKey = key,
LargeImageText = text,
},
Timestamps = Timestamps.Now,
});

private static bool CheckGlobal(Process process)
{
var path = GetPathOfWindow(process);
var file = Path.Combine(Path.GetDirectoryName(path)!, "config.ini");

if (!File.Exists(file))
throw new FileNotFoundException("Config not found");

var value = GetIniSectionValue(file, "General", "cps", "gw_PC");

return value is not ("gw_PC" or "bilibili_PC");
}

private static string GetIniSectionValue(string file, string section, string key, string defaultVal = null)
{
var stringBuilder = new StringBuilder(1024);
GetPrivateProfileString(section, key, defaultVal, stringBuilder, 1024, file);
return stringBuilder.ToString();
}

[DllImport("kernel32.dll")]
private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retval, int size, string filePath);

[DllImport("user32.dll")]
private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

private static string GetPathOfWindow(Process process)
{
try
{
return process.MainModule!.FileName;
}
catch (Exception e)
{
Debug.Print(e.ToString());
}

try
{
using var searcher = new ManagementObjectSearcher("SELECT ProcessId, ExecutablePath, CommandLine FROM Win32_Process");
using var collection = searcher.Get();
var results = collection.Cast<ManagementObject>();

foreach (var item in results)
{
var id = (int)(uint)item["ProcessId"];
var path = (string)item["ExecutablePath"];

if (id == process.Id)
{
return path;
}
}
}
catch (Exception e)
{
Debug.Print(e.ToString());
}

throw new InvalidOperationException("Failed to get path of handle");
}
}
4 changes: 2 additions & 2 deletions src/Properties/AssemblyInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,5 +32,5 @@
//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值
//通过使用 "*",如下所示:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyVersion("1.0.1.0")]
[assembly: AssemblyFileVersion("1.0.1.0")]
73 changes: 73 additions & 0 deletions src/Properties/app.manifest
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
<?xml version="1.0" encoding="utf-8"?>
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
<assemblyIdentity version="1.0.0.0" name="MyApplication.app" />
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
<security>
<requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
<!-- UAC 清单选项
如果想要更改 Windows 用户帐户控制级别,请使用
以下节点之一替换 requestedExecutionLevel 节点。
<requestedExecutionLevel level="asInvoker" uiAccess="false" />
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
<requestedExecutionLevel level="highestAvailable" uiAccess="false" />
指定 requestedExecutionLevel 元素将禁用文件和注册表虚拟化。
如果你的应用程序需要此虚拟化来实现向后兼容性,则移除此
元素。
-->
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
</requestedPrivileges>
<applicationRequestMinimum>
<defaultAssemblyRequest permissionSetReference="Custom" />
<PermissionSet class="System.Security.PermissionSet" version="1" Unrestricted="true" ID="Custom" SameSite="site" />
</applicationRequestMinimum>
</security>
</trustInfo>
<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
<application>
<!-- 设计此应用程序与其一起工作且已针对此应用程序进行测试的
Windows 版本的列表。取消评论适当的元素,
Windows 将自动选择最兼容的环境。 -->
<!-- Windows Vista -->
<!--<supportedOS Id="{e2011457-1546-43c5-a5fe-008deee3d3f0}" />-->
<!-- Windows 7 -->
<!--<supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}" />-->
<!-- Windows 8 -->
<!--<supportedOS Id="{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}" />-->
<!-- Windows 8.1 -->
<!--<supportedOS Id="{1f676c76-80e1-4239-95bb-83d0f6d0da78}" />-->
<!-- Windows 10 -->
<!--<supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}" />-->
</application>
</compatibility>
<!-- 指示该应用程序可感知 DPI 且 Windows 在 DPI 较高时将不会对其进行
自动缩放。Windows Presentation Foundation (WPF)应用程序自动感知 DPI,无需
选择加入。选择加入此设置的 Windows 窗体应用程序(面向 .NET Framework 4.6)还应
在其 app.config 中将 "EnableWindowsFormsHighDpiAutoResizing" 设置设置为 "true"。
将应用程序设为感知长路径。请参阅 https://docs.microsoft.com/windows/win32/fileio/maximum-file-path-limitation -->
<!--
<application xmlns="urn:schemas-microsoft-com:asm.v3">
<windowsSettings>
<dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true</dpiAware>
<longPathAware xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">true</longPathAware>
</windowsSettings>
</application>
-->
<!-- 启用 Windows 公共控件和对话框的主题(Windows XP 和更高版本) -->
<!--
<dependency>
<dependentAssembly>
<assemblyIdentity
type="win32"
name="Microsoft.Windows.Common-Controls"
version="6.0.0.0"
processorArchitecture="*"
publicKeyToken="6595b64144ccf1df"
language="*"
/>
</dependentAssembly>
</dependency>
-->
</assembly>
5 changes: 5 additions & 0 deletions src/StarRailRpc.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,9 @@
<GenerateManifests>false</GenerateManifests>
</PropertyGroup>
<PropertyGroup />
<PropertyGroup>
<ApplicationManifest>Properties\app.manifest</ApplicationManifest>
</PropertyGroup>
<ItemGroup>
<Reference Include="DiscordRPC, Version=1.1.3.18, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\DiscordRichPresence.1.1.3.18\lib\net45\DiscordRPC.dll</HintPath>
Expand All @@ -71,6 +74,7 @@
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Management" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
Expand All @@ -96,6 +100,7 @@
<DesignTime>True</DesignTime>
</Compile>
<None Include="packages.config" />
<None Include="Properties\app.manifest" />
<None Include="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.Designer.cs</LastGenOutput>
Expand Down

0 comments on commit 5cfb6e5

Please sign in to comment.