diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..296f0ee --- /dev/null +++ b/.gitignore @@ -0,0 +1,362 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd \ No newline at end of file diff --git a/Images/icon.png b/Images/icon.png new file mode 100644 index 0000000..30bde73 Binary files /dev/null and b/Images/icon.png differ diff --git a/Images/icon.svg b/Images/icon.svg new file mode 100644 index 0000000..34869aa --- /dev/null +++ b/Images/icon.svg @@ -0,0 +1,2 @@ + + diff --git a/Images/screenshot1.png b/Images/screenshot1.png new file mode 100644 index 0000000..a8605ec Binary files /dev/null and b/Images/screenshot1.png differ diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..a0ea79e --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 Anderson Urbano + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..7c198a4 --- /dev/null +++ b/README.md @@ -0,0 +1,32 @@ +[![MIT license](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/urbanoanderson/xinput-windows-manager/blob/master/LICENSE) + +# Xinput Windows Manager + + + +## About + +This system tray windows application allows the user to toggle a mouse mode by pressing a special button combination on an Xinput gamepad such as the Xbox One Controller. In this mode, the gamepad is able to freely move the cursor around the screen, perform left and right click actions as well as some useful keyboard presses. + +The software was developed so that users with a desktop setup with only gamepad input or at least inconvenient access to keyboard and mouse can perform basic tasks that require these input methods using a gamepad. An example would be my case, where I use a desktop PC with Steam Big Picture in my living room as a DIY game console. + + + +## Installation + +TODO + +## Usage + +TODO + +## Release Notes + +### 1.0.0 + +- Initial version +- Enables mouse movement, left and right click actions + +## Acknowledgements + +
Icon made by Kiranshastry from www.flaticon.com
\ No newline at end of file diff --git a/XinputWindowsManager.sln b/XinputWindowsManager.sln new file mode 100644 index 0000000..f055bea --- /dev/null +++ b/XinputWindowsManager.sln @@ -0,0 +1,32 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.30320.27 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "XinputWindowsManager", "XinputWindowsManager\XinputWindowsManager.csproj", "{18327177-3508-4205-83CA-373C4EF80E1F}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{D37B71AF-4A0C-487E-A667-5ABD5807D941}" + ProjectSection(SolutionItems) = preProject + .gitignore = .gitignore + LICENSE = LICENSE + README.md = README.md + EndProjectSection +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {18327177-3508-4205-83CA-373C4EF80E1F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {18327177-3508-4205-83CA-373C4EF80E1F}.Debug|Any CPU.Build.0 = Debug|Any CPU + {18327177-3508-4205-83CA-373C4EF80E1F}.Release|Any CPU.ActiveCfg = Release|Any CPU + {18327177-3508-4205-83CA-373C4EF80E1F}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {7743E5E2-F915-478B-A1CA-2E265A043F49} + EndGlobalSection +EndGlobal diff --git a/XinputWindowsManager/DesktopManagerService.cs b/XinputWindowsManager/DesktopManagerService.cs new file mode 100644 index 0000000..7434da3 --- /dev/null +++ b/XinputWindowsManager/DesktopManagerService.cs @@ -0,0 +1,105 @@ +using System; +using System.Diagnostics; +using System.Drawing; +using System.Threading.Tasks; +using SharpDX.XInput; + +namespace XinputWindowsManager +{ + public class DesktopManagerService + { + private const double MAX_CURSOR_MOVEMENT_SPEED = 25.0; + + private const double THUMBSTICK_MOVEMENT_THRESHOLD = 0.3; + + private static TimeSpan FRAME_TIME = TimeSpan.FromSeconds(1 / 120.0); + + private readonly XinputController gamepad; + + private readonly Stopwatch frameCounter; + + public DesktopManagerService() + { + this.gamepad = new XinputController(UserIndex.One); + this.frameCounter = new Stopwatch(); + this.ServiceRunning = false; + this.MouseModeOn = false; + } + + public event EventHandler OnMouseModeToggled; + + public bool ServiceRunning { get; private set; } + + public bool MouseModeOn { get; private set; } + + public void Stop() + { + this.MouseModeOn = false; + this.ServiceRunning = false; + } + + public void Start() + { + this.ServiceRunning = true; + this.frameCounter.Start(); + + while (this.ServiceRunning) + { + if (this.gamepad.ButtonPressed(GamepadButtonFlags.Start)) + this.ToggleMouseMode(); + + if (MouseModeOn) + this.ProcessMouseMode(); + + this.PoolXinputController(); + } + } + + public void ToggleMouseMode() + { + this.MouseModeOn = !this.MouseModeOn; + Debug.WriteLine($"Switching mouse mode to '{this.MouseModeOn}'"); + Console.Beep(); + this.OnMouseModeToggled?.Invoke(this, this.MouseModeOn); + } + + private void PoolXinputController() + { + this.gamepad.Pool(); + TimeSpan elapsedTime = this.frameCounter.Elapsed; + this.frameCounter.Reset(); + + if (FRAME_TIME > elapsedTime) + Task.Delay(FRAME_TIME - elapsedTime).Wait(); + } + + private void ProcessMouseMode() + { + // Move mouse cursor with left thumb stick + double leftStickX = gamepad.LeftStickXState(); + double leftStickY = gamepad.LeftStickYState(); + + if (leftStickX > THUMBSTICK_MOVEMENT_THRESHOLD || leftStickX < -THUMBSTICK_MOVEMENT_THRESHOLD + || leftStickY > THUMBSTICK_MOVEMENT_THRESHOLD || leftStickY < -THUMBSTICK_MOVEMENT_THRESHOLD) + { + Point mousePos = WindowsMouseCursor.GetPosition(); + int newX = (int)(mousePos.X + (leftStickX * MAX_CURSOR_MOVEMENT_SPEED)); + int newY = (int)(mousePos.Y - (leftStickY * MAX_CURSOR_MOVEMENT_SPEED)); + Debug.WriteLine($"New cursor pos: x={mousePos.X}, y={mousePos.Y}"); + WindowsMouseCursor.SetPosition(newX, newY); + } + + // Left click with mouse cursor if A button is pressed + if (gamepad.ButtonPressed(GamepadButtonFlags.A)) + { + Debug.WriteLine("Sending left click input..."); + WindowsMouseCursor.SendLeftClick(); + } + if (gamepad.ButtonPressed(GamepadButtonFlags.X)) + { + Debug.WriteLine("Sending right click input..."); + WindowsMouseCursor.SendRightClick(); + } + } + } +} diff --git a/XinputWindowsManager/Program.cs b/XinputWindowsManager/Program.cs new file mode 100644 index 0000000..b87cb98 --- /dev/null +++ b/XinputWindowsManager/Program.cs @@ -0,0 +1,21 @@ +using System; +using System.Windows.Forms; + +namespace XinputWindowsManager +{ + public static class Program + { + /// + /// The main entry point for the application. + /// + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + SystemTrayApplicationContext appContext = new SystemTrayApplicationContext(); + Application.ApplicationExit += appContext.HandleExit; + Application.Run(appContext); + } + } +} diff --git a/XinputWindowsManager/Properties/Resources.Designer.cs b/XinputWindowsManager/Properties/Resources.Designer.cs new file mode 100644 index 0000000..085fc52 --- /dev/null +++ b/XinputWindowsManager/Properties/Resources.Designer.cs @@ -0,0 +1,73 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace XinputWindowsManager.Properties { + using System; + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [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("XinputWindowsManager.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + + /// + /// Looks up a localized resource of type System.Drawing.Icon similar to (Icon). + /// + internal static System.Drawing.Icon AppIcon { + get { + object obj = ResourceManager.GetObject("AppIcon", resourceCulture); + return ((System.Drawing.Icon)(obj)); + } + } + } +} diff --git a/XinputWindowsManager/Properties/Resources.resx b/XinputWindowsManager/Properties/Resources.resx new file mode 100644 index 0000000..6a1b0ea --- /dev/null +++ b/XinputWindowsManager/Properties/Resources.resx @@ -0,0 +1,124 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + + ..\icon.ico;System.Drawing.Icon, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + \ No newline at end of file diff --git a/XinputWindowsManager/SystemTrayApplicationContext.cs b/XinputWindowsManager/SystemTrayApplicationContext.cs new file mode 100644 index 0000000..d87a617 --- /dev/null +++ b/XinputWindowsManager/SystemTrayApplicationContext.cs @@ -0,0 +1,80 @@ +using System; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace XinputWindowsManager +{ + public class SystemTrayApplicationContext : ApplicationContext + { + private const string APPLICATION_NAME = "Xinput Windows Manager"; + + private const string TOGGLE_LABEL_TEXT_FORMAT = "Toggle Mouse Mode {0}"; + + private const string EXIT_LABEL_TEXT = "Exit"; + + private readonly DesktopManagerService desktopManagerService; + + private NotifyIcon trayIcon; + + private ContextMenuStrip contextMenuStrip; + + private ToolStripMenuItem toggleLabel; + + private ToolStripMenuItem exitLabel; + + public SystemTrayApplicationContext() + { + this.SetupContextMenu(); + + this.desktopManagerService = new DesktopManagerService(); + this.desktopManagerService.OnMouseModeToggled += this.HandleMouseModeToggle; + + this.UpdateToggleLabel(false); + Task.Factory.StartNew(() => this.desktopManagerService.Start()); + } + + public void HandleExit(object sender, EventArgs e) + { + this.desktopManagerService.Stop(); + trayIcon.Visible = false; // Hide tray icon, otherwise it will remain shown until user mouses over it + Application.Exit(); + } + + private void HandleMouseModeToggle(object o, bool mouseModeOn) + { + this.contextMenuStrip.BeginInvoke((Action)(() => + { + this.UpdateToggleLabel(mouseModeOn); + })); + } + + private void SetupContextMenu() + { + this.toggleLabel = new ToolStripMenuItem(); + this.toggleLabel.Anchor = AnchorStyles.Right; + this.toggleLabel.Click += (o, e) => this.desktopManagerService.ToggleMouseMode(); + + this.exitLabel = new ToolStripMenuItem(EXIT_LABEL_TEXT); + this.exitLabel.Anchor = AnchorStyles.Right; + this.exitLabel.Click += this.HandleExit; + + this.contextMenuStrip = new ContextMenuStrip(); + this.contextMenuStrip.ShowImageMargin = false; + this.contextMenuStrip.Items.Add(toggleLabel); + this.contextMenuStrip.Items.Add(exitLabel); + + this.trayIcon = new NotifyIcon() + { + Icon = Properties.Resources.AppIcon, + Visible = true, + Text = APPLICATION_NAME, + ContextMenuStrip = this.contextMenuStrip, + }; + } + + private void UpdateToggleLabel(bool mouseModeOn) + { + this.toggleLabel.Text = string.Format(TOGGLE_LABEL_TEXT_FORMAT, mouseModeOn ? "Off" : "On"); + } + } +} diff --git a/XinputWindowsManager/WindowsMouseCursor.cs b/XinputWindowsManager/WindowsMouseCursor.cs new file mode 100644 index 0000000..2c8c0e7 --- /dev/null +++ b/XinputWindowsManager/WindowsMouseCursor.cs @@ -0,0 +1,47 @@ +using System; +using System.Drawing; +using System.Runtime.InteropServices; + +namespace XinputWindowsManager +{ + public class WindowsMouseCursor + { + [DllImport("user32.dll")] + private static extern bool GetCursorPos(out Point lpPoint); + + [DllImport("user32")] + private static extern int SetCursorPos(int x, int y); + + [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] + public static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint cButtons, UIntPtr dwExtraInfo); + private const uint MOUSEEVENTF_LEFTDOWN = 0x02; + private const uint MOUSEEVENTF_LEFTUP = 0x04; + private const uint MOUSEEVENTF_RIGHTDOWN = 0x08; + private const uint MOUSEEVENTF_RIGHTUP = 0x10; + + public static Point GetPosition() + { + Point position = default; + GetCursorPos(out position); + + return position; + } + + public static void SetPosition(int x, int y) + { + SetCursorPos(x, y); + } + + public static void SendLeftClick() + { + Point p = GetPosition(); + mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, (uint)p.X, (uint)p.Y, 0, (UIntPtr)0); + } + + public static void SendRightClick() + { + Point p = GetPosition(); + mouse_event(MOUSEEVENTF_RIGHTDOWN | MOUSEEVENTF_RIGHTUP, (uint)p.X, (uint)p.Y, 0, (UIntPtr)0); + } + } +} diff --git a/XinputWindowsManager/XinputController.cs b/XinputWindowsManager/XinputController.cs new file mode 100644 index 0000000..821023b --- /dev/null +++ b/XinputWindowsManager/XinputController.cs @@ -0,0 +1,167 @@ +using SharpDX.XInput; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +namespace XinputWindowsManager +{ + public class XinputController : IDisposable + { + private const double MAX_TRIGGER_VALUE = 255.0; + + private const double MAX_AXIS_VALUE = 32767.0; + + private Controller gamepad; + + private State gamepadState; + + private IDictionary buttonStates; + + private CancellationTokenSource poolingCts; + public XinputController(UserIndex gamepadIndex = UserIndex.One) + { + this.gamepad = new Controller(gamepadIndex); + this.buttonStates = new Dictionary(); + + this.buttonStates.Add(GamepadButtonFlags.Start, (false, false)); + this.buttonStates.Add(GamepadButtonFlags.Back, (false, false)); + this.buttonStates.Add(GamepadButtonFlags.A, (false, false)); + this.buttonStates.Add(GamepadButtonFlags.B, (false, false)); + this.buttonStates.Add(GamepadButtonFlags.X, (false, false)); + this.buttonStates.Add(GamepadButtonFlags.Y, (false, false)); + this.buttonStates.Add(GamepadButtonFlags.LeftShoulder, (false, false)); + this.buttonStates.Add(GamepadButtonFlags.RightShoulder, (false, false)); + this.buttonStates.Add(GamepadButtonFlags.LeftThumb, (false, false)); + this.buttonStates.Add(GamepadButtonFlags.RightThumb, (false, false)); + this.buttonStates.Add(GamepadButtonFlags.DPadUp, (false, false)); + this.buttonStates.Add(GamepadButtonFlags.DPadDown, (false, false)); + this.buttonStates.Add(GamepadButtonFlags.DPadLeft, (false, false)); + this.buttonStates.Add(GamepadButtonFlags.DPadRight, (false, false)); + } + + public event EventHandler OnButtonPressed; + + public event EventHandler OnButtonReleased; + + public bool IsPooling + { + get + { + return this.poolingCts != null && !this.poolingCts.IsCancellationRequested; + } + } + + public void Pool() + { + this.gamepadState = gamepad.GetState(); + + this.UpdateButtonState(GamepadButtonFlags.Back); + this.UpdateButtonState(GamepadButtonFlags.Start); + this.UpdateButtonState(GamepadButtonFlags.A); + this.UpdateButtonState(GamepadButtonFlags.B); + this.UpdateButtonState(GamepadButtonFlags.X); + this.UpdateButtonState(GamepadButtonFlags.Y); + this.UpdateButtonState(GamepadButtonFlags.LeftShoulder); + this.UpdateButtonState(GamepadButtonFlags.RightShoulder); + this.UpdateButtonState(GamepadButtonFlags.LeftThumb); + this.UpdateButtonState(GamepadButtonFlags.RightThumb); + this.UpdateButtonState(GamepadButtonFlags.DPadUp); + this.UpdateButtonState(GamepadButtonFlags.DPadDown); + this.UpdateButtonState(GamepadButtonFlags.DPadLeft); + this.UpdateButtonState(GamepadButtonFlags.DPadRight); + } + + public void StartPooling() + { + if (!this.IsPooling) + { + this.poolingCts = new CancellationTokenSource(); + + Task.Factory.StartNew(() => { + while (!this.poolingCts.IsCancellationRequested) + this.Pool(); + }); + } + } + + public void StopPooling() + { + if (this.IsPooling) + { + this.poolingCts.Cancel(); + this.poolingCts.Dispose(); + this.poolingCts = null; + } + } + + public void Dispose() + { + this.StopPooling(); + } + + public bool ButtonState(GamepadButtonFlags button) + { + return this.buttonStates[button].Item2; + } + + public bool ButtonPressed(GamepadButtonFlags button) + { + return !this.buttonStates[button].Item1 && this.buttonStates[button].Item2; + } + + public bool ButtonHolded(GamepadButtonFlags button) + { + return this.buttonStates[button].Item1 && this.buttonStates[button].Item2; + } + + public bool ButtonReleased(GamepadButtonFlags button) + { + return this.buttonStates[button].Item1 && !this.buttonStates[button].Item2; + } + + public double LeftTriggerState() + { + return this.gamepadState.Gamepad.LeftTrigger / MAX_TRIGGER_VALUE; + } + + public double RightTriggerState() + { + return this.gamepadState.Gamepad.RightTrigger / MAX_TRIGGER_VALUE; + } + + public double LeftStickXState() + { + return this.gamepadState.Gamepad.LeftThumbX / MAX_AXIS_VALUE; + } + + public double LeftStickYState() + { + return this.gamepadState.Gamepad.LeftThumbY / MAX_AXIS_VALUE; + } + + public double RightStickXState() + { + return this.gamepadState.Gamepad.RightThumbX / MAX_AXIS_VALUE; + } + + public double RightStickYState() + { + return this.gamepadState.Gamepad.RightThumbY / MAX_AXIS_VALUE; + } + + private void UpdateButtonState(GamepadButtonFlags button) + { + this.buttonStates[button] = (this.buttonStates[button].Item2, this.gamepadState.Gamepad.Buttons.HasFlag(button)); + + if (!this.buttonStates[button].Item1 && this.buttonStates[button].Item2) + { + this.OnButtonPressed?.Invoke(this, button); + } + else if (this.buttonStates[button].Item1 && !this.buttonStates[button].Item2) + { + this.OnButtonReleased?.Invoke(this, button); + } + } + } +} diff --git a/XinputWindowsManager/XinputWindowsManager.csproj b/XinputWindowsManager/XinputWindowsManager.csproj new file mode 100644 index 0000000..ce41d1f --- /dev/null +++ b/XinputWindowsManager/XinputWindowsManager.csproj @@ -0,0 +1,28 @@ + + + + WinExe + netcoreapp3.1 + true + + + + + + + + + True + True + Resources.resx + + + + + + ResXFileCodeGenerator + Resources.Designer.cs + + + + \ No newline at end of file diff --git a/XinputWindowsManager/icon.ico b/XinputWindowsManager/icon.ico new file mode 100644 index 0000000..2b42726 Binary files /dev/null and b/XinputWindowsManager/icon.ico differ