Compare commits

..

2 Commits

9 changed files with 498 additions and 516 deletions

3
.clang-format Normal file
View File

@@ -0,0 +1,3 @@
BasedOnStyle: Google
IndentWidth: 4
ColumnLimit: 120

View File

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

View File

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

View File

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

View File

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

View File

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

@@ -6,289 +6,281 @@ using System.Runtime.InteropServices;
using System.Windows.Forms; using System.Windows.Forms;
namespace DD2Switcher { namespace DD2Switcher {
internal static class Program { internal static class Program {
private static int NumProc = 19; private static int NumProc = 19;
private static Process[] windows = new Process[NumProc]; private static Process[] windows = new Process[NumProc];
private static int ActiveIndex = -1; private static int ActiveIndex = -1;
private static readonly IntPtr defaultAffinity = new(0xFF000000); private static readonly IntPtr defaultAffinity = new(0xFF000000);
private static readonly IntPtr fullAffinity = new(0xFFFFFFFF); private static readonly IntPtr fullAffinity = new(0xFFFFFFFF);
[DllImport("user32.dll")] [DllImport("user32.dll")]
public static extern IntPtr GetForegroundWindow(); public static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")] [DllImport("user32.dll")]
public static extern bool SetForegroundWindow(IntPtr hWnd); public static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")] [DllImport("user32.dll")]
private static extern short GetKeyState(int nVirtKey); private static extern short GetKeyState(int nVirtKey);
[DllImport("kernel32.dll", SetLastError = true)] [DllImport("kernel32.dll", SetLastError = true)]
[return:MarshalAs(UnmanagedType.Bool)] [return:MarshalAs(UnmanagedType.Bool)]
static extern bool AllocConsole(); static extern bool AllocConsole();
[DllImport("user32.dll")] [DllImport("user32.dll")]
private static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, private static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, int dwExtraInfo);
int dwExtraInfo);
private static void CleanWindows() { private static void CleanWindows() {
for (int i = 0; i < NumProc; i++) { for (int i = 0; i < NumProc; i++) {
var window = windows[i]; var window = windows[i];
if (window == null) if (window == null)
continue; continue;
if (window.MainWindowHandle == IntPtr.Zero) { if (window.MainWindowHandle == IntPtr.Zero) {
Console.WriteLine( Console.WriteLine($"Window at index {i} has no main window, removing from tracked windows");
$"Window at index {i} has no main window, removing from tracked windows"); windows[i] = null;
windows[i] = null; }
} }
}
}
private static void AdjustAffinities() {
CleanWindows();
for (int i = 0; i < NumProc; i++) {
var window = windows[i];
if (window == null)
continue;
if (i != ActiveIndex) {
try {
window.ProcessorAffinity = defaultAffinity;
} catch (Exception e) {
windows[i] = null;
} }
}
}
var active = windows[ActiveIndex]; private static void AdjustAffinities() {
if (active != null) { CleanWindows();
try { for (int i = 0; i < NumProc; i++) {
active.ProcessorAffinity = fullAffinity; var window = windows[i];
} catch (Exception e) { if (window == null)
windows[ActiveIndex] = null; continue;
} if (i != ActiveIndex) {
} try {
} window.ProcessorAffinity = defaultAffinity;
} catch (Exception e) {
windows[i] = null;
}
}
}
private static void AdjustPriorities() { var active = windows[ActiveIndex];
CleanWindows(); if (active != null) {
for (int i = 0; i < NumProc; i++) { try {
var window = windows[i]; active.ProcessorAffinity = fullAffinity;
if (window == null) } catch (Exception e) {
continue; windows[ActiveIndex] = null;
}
if (i != ActiveIndex) { }
try {
window.PriorityClass = ProcessPriorityClass.Idle;
} catch (Exception e) {
windows[i] = null;
} }
}
}
var active = windows[ActiveIndex]; private static void AdjustPriorities() {
if (active != null) { CleanWindows();
try { for (int i = 0; i < NumProc; i++) {
active.PriorityClass = ProcessPriorityClass.High; var window = windows[i];
} catch (Exception e) { if (window == null)
windows[ActiveIndex] = null; continue;
}
}
}
private static Process GetForegroundProcess() { if (i != ActiveIndex) {
var foregroundWindow = GetForegroundWindow(); try {
var process = Process.GetProcesses(); window.PriorityClass = ProcessPriorityClass.Idle;
Process foregroundProcess = null; } catch (Exception e) {
foreach (var p in process) windows[i] = null;
if (foregroundWindow == p.MainWindowHandle) { }
foregroundProcess = p; }
break; }
}
if (foregroundProcess == null) var active = windows[ActiveIndex];
return null; if (active != null) {
return foregroundProcess; try {
} active.PriorityClass = ProcessPriorityClass.High;
} catch (Exception e) {
windows[ActiveIndex] = null;
}
}
}
private static Boolean ProcessTracked(int id) { private static Process GetForegroundProcess() {
for (int i = 0; i < NumProc; i++) { var foregroundWindow = GetForegroundWindow();
if (windows[i] != null && windows[i].Id == id) { var process = Process.GetProcesses();
return true; Process foregroundProcess = null;
} foreach (var p in process)
} if (foregroundWindow == p.MainWindowHandle) {
foregroundProcess = p;
break;
}
return false; if (foregroundProcess == null)
} return null;
return foregroundProcess;
}
private static void Track(Process process) { private static Boolean ProcessTracked(int id) {
// First find the first null slot for (int i = 0; i < NumProc; i++) {
int firstNullIndex = -1; if (windows[i] != null && windows[i].Id == id) {
for (int i = 0; i < NumProc; i++) { return true;
if (windows[i] == null) { }
firstNullIndex = i; }
break;
}
}
if (firstNullIndex == -1) { return false;
Console.WriteLine("No slots available for tracking"); }
return;
}
// Compact the array by shifting non-null elements to the left private static void Track(Process process) {
for (int i = firstNullIndex + 1; i < NumProc; i++) { // First find the first null slot
if (windows[i] != null) { int firstNullIndex = -1;
windows[firstNullIndex] = windows[i]; for (int i = 0; i < NumProc; i++) {
windows[i] = null; if (windows[i] == null) {
firstNullIndex++; firstNullIndex = i;
} break;
} }
}
// Add the new process at the first null slot if (firstNullIndex == -1) {
windows[firstNullIndex] = process; Console.WriteLine("No slots available for tracking");
Console.WriteLine( return;
$"Added {process.ProcessName} to tracked windows at index {firstNullIndex}"); }
}
// private static void TrackWows() { // Compact the array by shifting non-null elements to the left
// CleanWindows(); for (int i = firstNullIndex + 1; i < NumProc; i++) {
// var processes = Process.GetProcesses().OrderBy(p => p.Id).ToList(); if (windows[i] != null) {
// foreach (var process in processes) { windows[firstNullIndex] = windows[i];
// if (process.ProcessName == "UWow-64") { windows[i] = null;
// Console.WriteLine($"Found UWow-64 at pid {process.Id}"); firstNullIndex++;
// if (ProcessTracked(process.Id)) }
// continue; }
// Track(process);
// }
// }
// }
private static void Swap(int index) { // Add the new process at the first null slot
index = (index - 1) % NumProc; windows[firstNullIndex] = process;
if (index < 0) Console.WriteLine($"Added {process.ProcessName} to tracked windows at index {firstNullIndex}");
index = NumProc - 1; }
if (index >= NumProc)
return;
CleanWindows();
Console.WriteLine($"Swapping window at index {index}");
var process = GetForegroundProcess();
if (process == null)
return;
Console.WriteLine($"Foreground process: {process}");
bool found = false;
for (int i = 0; i < NumProc; i++) { // private static void TrackWows() {
var window = windows[i]; // CleanWindows();
if (window != null && window.Id == process.Id) { // var processes = Process.GetProcesses().OrderBy(p => p.Id).ToList();
found = true; // foreach (var process in processes) {
break; // if (process.ProcessName == "UWow-64") {
} // Console.WriteLine($"Found UWow-64 at pid {process.Id}");
} // if (ProcessTracked(process.Id))
// continue;
// Track(process);
// }
// }
// }
if (!found) { private static void Swap(int index) {
for (int i = 0; i < NumProc; i++) { index = (index - 1) % NumProc;
var window = windows[i]; if (index < 0)
if (window == null) { index = NumProc - 1;
Console.WriteLine( if (index >= NumProc)
$"Adding foreground window to tracked at index {i}..."); return;
windows[i] = process; CleanWindows();
Console.WriteLine($"Swapping window at index {index}");
var process = GetForegroundProcess();
if (process == null)
return;
Console.WriteLine($"Foreground process: {process}");
bool found = false;
for (int i = 0; i < NumProc; i++) {
var window = windows[i];
if (window != null && window.Id == process.Id) {
found = true;
break;
}
}
if (!found) {
for (int i = 0; i < NumProc; i++) {
var window = windows[i];
if (window == null) {
Console.WriteLine($"Adding foreground window to tracked at index {i}...");
windows[i] = process;
break; break;
}
}
}
for (int i = 0; i < NumProc; i++) {
var window = windows[i];
if (window != null && window.Id == process.Id) {
windows[i] = windows[index];
windows[index] = window;
Console.WriteLine($"Swapped window at index {i} to {index}");
// Toggle caps lock off
keybd_event(0x14, 0, 0, 0); // KEYEVENTF_KEYDOWN
keybd_event(0x14, 0, 0x0002, 0); // KEYEVENTF_KEYUP
return;
}
}
} }
}
}
for (int i = 0; i < NumProc; i++) { private static void TabTo(int index) {
var window = windows[i]; index = (index - 1) % NumProc;
if (window != null && window.Id == process.Id) { if (index < 0)
windows[i] = windows[index]; index = NumProc - 1;
windows[index] = window; if (index >= NumProc)
Console.WriteLine($"Swapped window at index {i} to {index}"); return;
// Toggle scroll lock off CleanWindows();
keybd_event(0x91, 0, 0, 0); // KEYEVENTF_KEYDOWN Console.WriteLine($"Tab to window at index {index}");
keybd_event(0x91, 0, 0x0002, 0); // KEYEVENTF_KEYUP
return;
}
}
}
private static void TabTo(int index) { var window = windows[index];
index = (index - 1) % NumProc; if (window == null || window.MainWindowHandle == IntPtr.Zero) {
if (index < 0) Console.WriteLine($"Window at index {index} does not exist, removing from tracked windows");
index = NumProc - 1; windows[index] = null;
if (index >= NumProc) } else {
return; SetForegroundWindow(window.MainWindowHandle);
CleanWindows(); ActiveIndex = index;
Console.WriteLine($"Tab to window at index {index}"); AdjustAffinities();
AdjustPriorities();
var window = windows[index]; }
if (window == null || window.MainWindowHandle == IntPtr.Zero) {
Console.WriteLine(
$"Window at index {index} does not exist, removing from tracked windows");
windows[index] = null;
} else {
SetForegroundWindow(window.MainWindowHandle);
ActiveIndex = index;
AdjustAffinities();
AdjustPriorities();
}
}
private static bool IsScrollLockOn() { return (GetKeyState(0x91) & 1) == 1; }
[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.Scroll, KeyModifiers.NoRepeat);
// Register main number keys (0-9)
for (int i = 0; i < 10; i++)
HotKeyManager.RegisterHotKey(Keys.D0 + i, KeyModifiers.Alt);
// Register numpad keys (1-9)
for (int i = 0; i < 9; i++)
HotKeyManager.RegisterHotKey(Keys.NumPad1 + i, KeyModifiers.Alt);
HotKeyManager.RegisterHotKey(Keys.Oemtilde, KeyModifiers.Alt);
HotKeyManager.HotKeyPressed += HotKeyManager_HotKeyPressed;
void HotKeyManager_HotKeyPressed(object sender, HotKeyEventArgs e) {
// if (e.Key == Keys.Oemtilde && e.Modifiers == KeyModifiers.Alt) {
// TrackWows();
// return;
// }
int index;
if (e.Key >= Keys.D0 && e.Key <= Keys.D9) {
index = e.Key - Keys.D0;
} else if (e.Key >= Keys.NumPad1 && e.Key <= Keys.NumPad9) {
index = 10 + (e.Key - Keys.NumPad1);
} else {
return;
}
if (e.Modifiers == KeyModifiers.Alt) {
if (IsScrollLockOn()) {
Swap(index);
} else {
TabTo(index);
} }
}
}
Console.CancelKeyPress += private static bool IsCapsLockOn() {
(sender, e) => { Process.GetCurrentProcess().Kill(); }; return (GetKeyState(0x14) & 1) == 1;
while (true) }
System.Threading.Thread.Sleep(100000);
} [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.Capital, KeyModifiers.NoRepeat);
// Register main number keys (0-9)
for (int i = 0; i < 10; i++) HotKeyManager.RegisterHotKey(Keys.D0 + i, KeyModifiers.Alt);
// Register numpad keys (1-9)
for (int i = 0; i < 9; i++) HotKeyManager.RegisterHotKey(Keys.NumPad1 + i, KeyModifiers.Alt);
HotKeyManager.RegisterHotKey(Keys.Oemtilde, KeyModifiers.Alt);
HotKeyManager.HotKeyPressed += HotKeyManager_HotKeyPressed;
void HotKeyManager_HotKeyPressed(object sender, HotKeyEventArgs e) {
// if (e.Key == Keys.Oemtilde && e.Modifiers == KeyModifiers.Alt) {
// TrackWows();
// return;
// }
int index;
if (e.Key >= Keys.D0 && e.Key <= Keys.D9) {
index = e.Key - Keys.D0;
} else if (e.Key >= Keys.NumPad1 && e.Key <= Keys.NumPad9) {
index = 10 + (e.Key - Keys.NumPad1);
} else {
return;
}
if (e.Modifiers == KeyModifiers.Alt) {
if (IsCapsLockOn()) {
Swap(index);
} else {
TabTo(index);
}
}
}
Console.CancelKeyPress += (sender, e) => { Process.GetCurrentProcess().Kill(); };
while (true) System.Threading.Thread.Sleep(100000);
}
}
} }

View File

@@ -9,55 +9,53 @@
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
namespace DD2Switcher.Properties { namespace DD2Switcher.Properties {
using System; using System;
/// <summary> /// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc. /// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary> /// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder // This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio. // class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen // To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project. // with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute( [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder",
"System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] "17.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources { internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture;
private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance",
"CA1811:AvoidUncalledPrivateCode")]
internal Resources() {}
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute( /// <summary>
"Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] /// Returns the cached ResourceManager instance used by this class.
internal Resources() {} /// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(
global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager(
"DD2Switcher.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary> /// <summary>
/// Returns the cached ResourceManager instance used by this class. /// Overrides the current thread's CurrentUICulture property for all
/// </summary> /// resource lookups using this strongly typed resource class.
[global::System.ComponentModel.EditorBrowsableAttribute( /// </summary>
global::System.ComponentModel.EditorBrowsableState.Advanced)] [global::System.ComponentModel.EditorBrowsableAttribute(
internal static global::System.Resources.ResourceManager ResourceManager { global::System.ComponentModel.EditorBrowsableState.Advanced)]
get { internal static global::System.Globalization.CultureInfo Culture {
if (object.ReferenceEquals(resourceMan, null)) { get { return resourceCulture; }
global::System.Resources.ResourceManager temp = set { resourceCulture = value; }
new global::System.Resources.ResourceManager( }
"DD2Switcher.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
} }
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(
global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get { return resourceCulture; }
set { resourceCulture = value; }
}
}
} }

View File

@@ -9,18 +9,16 @@
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
namespace DD2Switcher.Properties { namespace DD2Switcher.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute(
"Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator",
"11.0.0.0")]
internal sealed partial class Settings
: global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance =
((Settings)(global::System.Configuration.ApplicationSettingsBase
.Synchronized(new Settings())));
public static Settings Default { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
get { return defaultInstance; } [global::System.CodeDom.Compiler.GeneratedCodeAttribute(
} "Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "17.14.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance =
((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get { return defaultInstance; }
}
}
} }
}