Compare commits

...

4 Commits

Author SHA1 Message Date
1d0ca3a6e0 Implement basic functionality of tabbing 2024-11-03 01:03:59 +01:00
180e8cb699 Add systray 2024-11-03 00:24:56 +01:00
5a323c78f8 Add basic go structure 2024-11-03 00:17:16 +01:00
451038a1a6 Delete everything 2024-11-02 23:21:48 +01:00
15 changed files with 128 additions and 510 deletions

6
.gitignore vendored
View File

@@ -1,5 +1 @@
.idea
**/Debug
**/Properties
obj
bin
main.log

View File

@@ -1,16 +0,0 @@

Microsoft Visual Studio Solution File, Format Version 12.00
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DD2Switcher", "DD2Switcher\DD2Switcher.csproj", "{2AC26899-8E27-4B96-85A9-C387186EAD27}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{2AC26899-8E27-4B96-85A9-C387186EAD27}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{2AC26899-8E27-4B96-85A9-C387186EAD27}.Debug|Any CPU.Build.0 = Debug|Any CPU
{2AC26899-8E27-4B96-85A9-C387186EAD27}.Release|Any CPU.ActiveCfg = Release|Any CPU
{2AC26899-8E27-4B96-85A9-C387186EAD27}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
EndGlobal

View File

@@ -1,5 +0,0 @@
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<s:String x:Key="/Default/CodeInspection/PencilsConfiguration/ActualSeverity/@EntryValue">INFO</s:String>
<s:String x:Key="/Default/Environment/Hierarchy/Build/BuildTool/CustomBuildToolPath/@EntryValue">C:\Users\Administrator\AppData\Local\JetBrains\Toolbox\apps\Rider\ch-0\231.8109.212\tools\MSBuild\Current\Bin\amd64\MSBuild.exe</s:String>
</wpf:ResourceDictionary>

View File

@@ -1,6 +0,0 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
</configuration>

View File

@@ -1,88 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')"/>
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{2AC26899-8E27-4B96-85A9-C387186EAD27}</ProjectGuid>
<OutputType>WinExe</OutputType>
<RootNamespace>DD2Switcher</RootNamespace>
<AssemblyName>DD2Switcher</AssemblyName>
<TargetFrameworkVersion>v4.8.1</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<Deterministic>true</Deterministic>
<LangVersion>10</LangVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>x64</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Prefer32bit>false</Prefer32bit>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>x64</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Prefer32bit>false</Prefer32bit>
</PropertyGroup>
<ItemGroup>
<Reference Include="System"/>
<Reference Include="System.Core"/>
<Reference Include="System.Xml.Linq"/>
<Reference Include="System.Data.DataSetExtensions"/>
<Reference Include="Microsoft.CSharp"/>
<Reference Include="System.Data"/>
<Reference Include="System.Deployment"/>
<Reference Include="System.Drawing"/>
<Reference Include="System.Net.Http"/>
<Reference Include="System.Windows.Forms"/>
<Reference Include="System.Xml"/>
</ItemGroup>
<ItemGroup>
<Compile Include="Form1.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="Form1.Designer.cs">
<DependentUpon>Form1.cs</DependentUpon>
</Compile>
<Compile Include="HotKeyManager.cs"/>
<Compile Include="Pixel.cs"/>
<Compile Include="Program.cs"/>
<Compile Include="Properties\AssemblyInfo.cs"/>
<EmbeddedResource Include="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
<SubType>Designer</SubType>
</EmbeddedResource>
<Compile Include="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<None Include="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.Designer.cs</LastGenOutput>
</None>
<Compile Include="Properties\Settings.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
</ItemGroup>
<ItemGroup>
<None Include="App.config"/>
</ItemGroup>
<ItemGroup>
<Content Include="beep.wav"/>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets"/>
</Project>

View File

@@ -1,40 +0,0 @@
namespace DD2Switcher
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Text = "Form1";
}
#endregion
}
}

View File

@@ -1,9 +0,0 @@
using System.Windows.Forms;
namespace DD2Switcher;
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
}

View File

@@ -1,105 +0,0 @@
using System;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;
namespace DD2Switcher;
public static class HotKeyManager {
private static volatile MessageWindow _wnd;
private static volatile IntPtr _hwnd;
private static readonly ManualResetEvent _windowReadyEvent = new(false);
private static int _id;
static HotKeyManager() {
var messageLoop = new Thread(delegate() { Application.Run(new MessageWindow()); });
messageLoop.Name = "MessageLoopThread";
messageLoop.IsBackground = true;
messageLoop.Start();
}
public static event EventHandler<HotKeyEventArgs> HotKeyPressed;
public static int RegisterHotKey(Keys key, KeyModifiers modifiers) {
_windowReadyEvent.WaitOne();
var id = Interlocked.Increment(ref _id);
_wnd.Invoke(new RegisterHotKeyDelegate(RegisterHotKeyInternal), _hwnd, id, (uint)modifiers, (uint)key);
return id;
}
public static void UnregisterHotKey(int id) {
_wnd.Invoke(new UnRegisterHotKeyDelegate(UnRegisterHotKeyInternal), _hwnd, id);
}
private static void RegisterHotKeyInternal(IntPtr hwnd, int id, uint modifiers, uint key) {
RegisterHotKey(hwnd, id, modifiers, key);
}
private static void UnRegisterHotKeyInternal(IntPtr hwnd, int id) {
UnregisterHotKey(_hwnd, id);
}
private static void OnHotKeyPressed(HotKeyEventArgs e) {
if (HotKeyPressed != null) HotKeyPressed(null, e);
}
[DllImport("user32", SetLastError = true)]
private static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);
[DllImport("user32", SetLastError = true)]
private static extern bool UnregisterHotKey(IntPtr hWnd, int id);
private delegate void RegisterHotKeyDelegate(IntPtr hwnd, int id, uint modifiers, uint key);
private delegate void UnRegisterHotKeyDelegate(IntPtr hwnd, int id);
private class MessageWindow : Form {
private const int WM_HOTKEY = 0x312;
public MessageWindow() {
_wnd = this;
_hwnd = Handle;
_windowReadyEvent.Set();
}
protected override void WndProc(ref Message m) {
if (m.Msg == WM_HOTKEY) {
var e = new HotKeyEventArgs(m.LParam);
OnHotKeyPressed(e);
}
base.WndProc(ref m);
}
protected override void SetVisibleCore(bool value) {
// Ensure the window never becomes visible
base.SetVisibleCore(false);
}
}
}
public class HotKeyEventArgs : EventArgs {
public readonly Keys Key;
public readonly KeyModifiers Modifiers;
public HotKeyEventArgs(Keys key, KeyModifiers modifiers) {
Key = key;
Modifiers = modifiers;
}
public HotKeyEventArgs(IntPtr hotKeyParam) {
var param = (uint)hotKeyParam.ToInt64();
Key = (Keys)((param & 0xffff0000) >> 16);
Modifiers = (KeyModifiers)(param & 0x0000ffff);
}
}
[Flags]
public enum KeyModifiers {
Alt = 1,
Control = 2,
Shift = 4,
Windows = 8,
NoRepeat = 0x4000
}

View File

@@ -1,25 +0,0 @@
using System.Diagnostics;
using System.Drawing;
namespace DD2Switcher;
public class Pixel {
public Pixel(int x, int y, int R, int G, int B) {
this.x = x;
this.y = y;
this.R = R;
this.G = G;
this.B = B;
}
private int x { get; }
private int y { get; }
private int R { get; }
private int G { get; }
private int B { get; }
public bool ProcessBitmap(Bitmap bmp) {
var tempPixel = bmp.GetPixel(x, y);
return tempPixel.R >= R && tempPixel.B >= B && tempPixel.G >= G;
}
}

View File

@@ -1,211 +0,0 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace DD2Switcher;
internal static class Program {
private static List<Process> processes = new();
private static Process activeProcess;
private static readonly IntPtr defaultAffinity = new(0xFF000000);
private static readonly IntPtr fullAffinity = new(0xFFFFFFFF);
[DllImport("user32.dll")]
public static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
public static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool AllocConsole();
private static void AdjustAffinities() {
List<Process> fuckedProcesses = new();
foreach (var process in processes)
if (process != activeProcess) {
try {
process.ProcessorAffinity = defaultAffinity;
}
catch (Exception e) {
fuckedProcesses.Add(process);
}
}
try {
activeProcess.ProcessorAffinity = fullAffinity;
}
catch (Exception e) {
fuckedProcesses.Add(activeProcess);
}
foreach (var fucked in fuckedProcesses)
processes.Remove(fucked);
}
private static void AdjustPriorities() {
List<Process> fuckedProcesses = new();
foreach (var process in processes) {
try {
process.PriorityClass = ProcessPriorityClass.Idle;
}
catch (Exception e) {
fuckedProcesses.Add(process);
}
}
try {
activeProcess.PriorityClass = ProcessPriorityClass.High;
}
catch (Exception e) {
fuckedProcesses.Add(activeProcess);
}
foreach (var fucked in fuckedProcesses)
processes.Remove(fucked);
}
private static void SwitchToProcess(int index) {
Console.WriteLine("Switching to process at index " + index);
if (index >= processes.Count) return;
var targetWindowHandle = processes[processes.Count - 1 - index].MainWindowHandle;
if (targetWindowHandle == IntPtr.Zero) {
processes.RemoveAt(processes.Count - 1 - index);
return;
}
SetForegroundWindow(targetWindowHandle);
activeProcess = processes[processes.Count - 1 - index];
AdjustAffinities();
AdjustPriorities();
}
private static void SwitchMainGame() {
var foregroundWindow = GetForegroundWindow();
Process foregroundGame = null;
var foregroundGameIndex = -1;
var exists = false;
foreach (var process in processes)
if (foregroundWindow == process.MainWindowHandle) {
exists = true;
foregroundGame = process;
foregroundGameIndex = processes.IndexOf(process);
break;
}
if (exists) {
var tempGame = processes[0];
processes[0] = foregroundGame;
processes[foregroundGameIndex] = tempGame;
}
}
private static void ToggleGame() {
Console.WriteLine("Toggling foreground window as tracked...");
var foregroundWindow = GetForegroundWindow();
var systemProcesses = Process.GetProcesses();
Process foregroundProcess = null;
foreach (var process in systemProcesses)
if (foregroundWindow == process.MainWindowHandle) {
foregroundProcess = process;
break;
}
if (foregroundProcess == null) return;
Console.WriteLine("Foreground process: " + foregroundProcess.ProcessName);
var existingProcess = processes.Find(process => process.Id == foregroundProcess.Id);
if (existingProcess != null) {
Console.WriteLine("Removing foreground process from tracked...");
processes.Remove(existingProcess);
}
else {
Console.WriteLine("Adding foreground process to tracked...");
processes.Add(foregroundProcess);
}
}
[STAThread]
private static void Main() {
// AllocConsole();
var processes = Process.GetProcesses();
var currentProcess = Process.GetCurrentProcess();
foreach (var process in processes)
if (process.Id != currentProcess.Id && process.ProcessName == currentProcess.ProcessName) {
process.Kill();
Process.GetCurrentProcess().Kill();
}
HotKeyManager.RegisterHotKey(Keys.D1, KeyModifiers.Alt);
HotKeyManager.RegisterHotKey(Keys.D2, KeyModifiers.Alt);
HotKeyManager.RegisterHotKey(Keys.D3, KeyModifiers.Alt);
HotKeyManager.RegisterHotKey(Keys.D4, KeyModifiers.Alt);
HotKeyManager.RegisterHotKey(Keys.D5, KeyModifiers.Alt);
HotKeyManager.RegisterHotKey(Keys.D6, KeyModifiers.Alt);
HotKeyManager.RegisterHotKey(Keys.D7, KeyModifiers.Alt);
HotKeyManager.RegisterHotKey(Keys.D8, KeyModifiers.Alt);
HotKeyManager.RegisterHotKey(Keys.D9, KeyModifiers.Alt);
HotKeyManager.RegisterHotKey(Keys.Oemtilde, KeyModifiers.Alt);
// HotKeyManager.RegisterHotKey(Keys.Q, KeyModifiers.Alt);
// HotKeyManager.RegisterHotKey(Keys.W, KeyModifiers.Alt);
// HotKeyManager.RegisterHotKey(Keys.R, KeyModifiers.Alt);
HotKeyManager.HotKeyPressed += HotKeyManager_HotKeyPressed;
var pixelList = new System.Collections.Generic.List<Pixel>();
// pixelList.Add(new Pixel(1401, 1234, 224, 224, 224));
pixelList.Add(new Pixel(1359, 1235, 220, 220, 220));
static void HotKeyManager_HotKeyPressed(object sender, HotKeyEventArgs e) {
switch (e.Key) {
case Keys.D1:
SwitchToProcess(0);
break;
case Keys.D2:
SwitchToProcess(1);
break;
case Keys.D3:
SwitchToProcess(2);
break;
case Keys.D4:
SwitchToProcess(3);
break;
case Keys.D5:
SwitchToProcess(4);
break;
case Keys.D6:
SwitchToProcess(5);
break;
case Keys.D7:
SwitchToProcess(6);
break;
case Keys.D8:
SwitchToProcess(7);
break;
case Keys.D9:
SwitchToProcess(8);
break;
case Keys.Oemtilde:
ToggleGame();
break;
}
}
Console.CancelKeyPress += (sender, e) => {
Process.GetCurrentProcess().Kill();
};
while (true)
System.Threading.Thread.Sleep(100000);
}
}

Binary file not shown.

BIN
duck2.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

14
go.mod Normal file
View File

@@ -0,0 +1,14 @@
module multiboxer
go 1.23.2
require (
fyne.io/systray v1.11.0
github.com/robotn/gohook v0.41.0
)
require (
github.com/godbus/dbus/v5 v5.1.0 // indirect
github.com/vcaesar/keycode v0.10.1 // indirect
golang.org/x/sys v0.15.0 // indirect
)

12
go.sum Normal file
View File

@@ -0,0 +1,12 @@
fyne.io/systray v1.11.0 h1:D9HISlxSkx+jHSniMBR6fCFOUjk1x/OOOJLa9lJYAKg=
fyne.io/systray v1.11.0/go.mod h1:RVwqP9nYMo7h5zViCBHri2FgjXF7H2cub7MAq4NSoLs=
github.com/godbus/dbus/v5 v5.1.0 h1:4KLkAxT3aOY8Li4FRJe/KvhoNFFxo0m6fNuFUO8QJUk=
github.com/godbus/dbus/v5 v5.1.0/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
github.com/robotn/gohook v0.41.0 h1:h1vK3w/UQpq0YkIiGnxm9Awv85W54esL0/NUYGueggo=
github.com/robotn/gohook v0.41.0/go.mod h1:FedpuAkVqzM5t67L5fcf3hSSCUDO9cM5YkWCw1U+nuc=
github.com/vcaesar/keycode v0.10.1 h1:0DesGmMAPWpYTCYddOFiCMKCDKgNnwiQa2QXindVUHw=
github.com/vcaesar/keycode v0.10.1/go.mod h1:JNlY7xbKsh+LAGfY2j4M3znVrGEm5W1R8s/Uv6BJcfQ=
github.com/vcaesar/tt v0.20.0 h1:9t2Ycb9RNHcP0WgQgIaRKJBB+FrRdejuaL6uWIHuoBA=
github.com/vcaesar/tt v0.20.0/go.mod h1:GHPxQYhn+7OgKakRusH7KJ0M5MhywoeLb8Fcffs/Gtg=
golang.org/x/sys v0.15.0 h1:h48lPFYpsTvQJZF4EKyI4aLHaev3CxivZmv7yZig9pc=
golang.org/x/sys v0.15.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=

101
main.go Normal file
View File

@@ -0,0 +1,101 @@
package main
import (
"fmt"
"io"
"log"
"os"
"slices"
"syscall"
// _ "embed"
"fyne.io/systray"
hook "github.com/robotn/gohook"
)
var (
us32 = syscall.MustLoadDLL("user32.dll")
SetForegroundWindow = us32.MustFindProc("SetForegroundWindow")
GetForegroundWindow = us32.MustFindProc("GetForegroundWindow")
)
// //go:embed duck2.jpg
// var icon []byte
var Error *log.Logger
var Warning *log.Logger
func init() {
log.SetFlags(log.Lmicroseconds | log.Lshortfile)
logFile, err := os.Create("main.log")
if err != nil {
log.Printf("Error creating log file: %v", err)
os.Exit(1)
}
logger := io.MultiWriter(os.Stdout, logFile)
log.SetOutput(logger)
Error = log.New(io.MultiWriter(logFile, os.Stderr, os.Stdout),
fmt.Sprintf("%sERROR:%s ", "\033[0;101m", "\033[0m"),
log.Lmicroseconds|log.Lshortfile)
Warning = log.New(io.MultiWriter(logFile, os.Stdout),
fmt.Sprintf("%sWarning:%s ", "\033[0;93m", "\033[0m"),
log.Lmicroseconds|log.Lshortfile)
}
var processes = []uintptr{}
func main() {
go systray.Run(onReady, nil)
hook.Register(hook.KeyDown, []string{"alt", "-"}, func(e hook.Event) {
hwnd, _, _ := GetForegroundWindow.Call()
if slices.Contains(processes, hwnd) {
processes = slices.DeleteFunc(processes, func(i uintptr) bool {
return i == hwnd
})
} else {
processes = append(processes, hwnd)
}
log.Printf("%#v", processes)
})
hook.Register(hook.KeyDown, []string{"alt", "1"}, func(e hook.Event) {
TabTo(0)
})
s := hook.Start()
<-hook.Process(s)
}
func TabTo(idx int) {
log.Printf("TabTo: %d", idx)
log.Printf("%+v", processes)
if idx > len(processes) {
Warning.Printf("idx %d is greater than length of processes %d", idx, len(processes))
return
}
hwnd := processes[idx]
if hwnd == 0 {
Warning.Printf("hwnd for idx %d is 0", idx)
return
}
SetForegroundWindow.Call(hwnd)
}
func onReady() {
// Icons no workey... idk why...
// systray error: unable to set icon: The operation completed successfully.
//systray.SetIcon(icon)
systray.SetTitle("Awesome App")
systray.SetTooltip("Pretty awesome超级棒")
mQuit := systray.AddMenuItem("Quit", "Quit the whole app")
go func() {
<-mQuit.ClickedCh
fmt.Println("Requesting quit")
systray.Quit()
os.Exit(0)
// TODO: Quit properly, not this exit bullshit
fmt.Println("Finished quitting")
}()
// Sets the icon of a menu item. Only available on Mac and Windows.
//mQuit.SetIcon(icon)
}