Meta - Replace WPF projects with Avalonia projects
No files matched your search
@@ -0,0 +1,454 @@
|
||||
## 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/
|
||||
|
||||
# Tye
|
||||
.tye/
|
||||
|
||||
# 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
|
||||
|
||||
##
|
||||
## Visual studio for Mac
|
||||
##
|
||||
|
||||
|
||||
# globs
|
||||
Makefile.in
|
||||
*.userprefs
|
||||
*.usertasks
|
||||
config.make
|
||||
config.status
|
||||
aclocal.m4
|
||||
install-sh
|
||||
autom4te.cache/
|
||||
*.tar.gz
|
||||
tarballs/
|
||||
test-results/
|
||||
|
||||
# Mac bundle stuff
|
||||
*.dmg
|
||||
*.app
|
||||
|
||||
# content below from: https://github.com/github/gitignore/blob/master/Global/macOS.gitignore
|
||||
# General
|
||||
.DS_Store
|
||||
.AppleDouble
|
||||
.LSOverride
|
||||
|
||||
# Icon must end with two \r
|
||||
Icon
|
||||
|
||||
|
||||
# Thumbnails
|
||||
._*
|
||||
|
||||
# Files that might appear in the root of a volume
|
||||
.DocumentRevisions-V100
|
||||
.fseventsd
|
||||
.Spotlight-V100
|
||||
.TemporaryItems
|
||||
.Trashes
|
||||
.VolumeIcon.icns
|
||||
.com.apple.timemachine.donotpresent
|
||||
|
||||
# Directories potentially created on remote AFP share
|
||||
.AppleDB
|
||||
.AppleDesktop
|
||||
Network Trash Folder
|
||||
Temporary Items
|
||||
.apdisk
|
||||
|
||||
# content below from: https://github.com/github/gitignore/blob/master/Global/Windows.gitignore
|
||||
# Windows thumbnail cache files
|
||||
Thumbs.db
|
||||
ehthumbs.db
|
||||
ehthumbs_vista.db
|
||||
|
||||
# Dump file
|
||||
*.stackdump
|
||||
|
||||
# Folder config file
|
||||
[Dd]esktop.ini
|
||||
|
||||
# Recycle Bin used on file shares
|
||||
$RECYCLE.BIN/
|
||||
|
||||
# Windows Installer files
|
||||
*.cab
|
||||
*.msi
|
||||
*.msix
|
||||
*.msm
|
||||
*.msp
|
||||
|
||||
# Windows shortcuts
|
||||
*.lnk
|
||||
|
||||
# JetBrains Rider
|
||||
.idea/
|
||||
*.sln.iml
|
||||
|
||||
##
|
||||
## Visual Studio Code
|
||||
##
|
||||
.vscode/*
|
||||
!.vscode/settings.json
|
||||
!.vscode/tasks.json
|
||||
!.vscode/launch.json
|
||||
!.vscode/extensions.json
|
||||
@@ -0,0 +1,12 @@
|
||||
<Application xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:ui="clr-namespace:Artemis.UI;assembly=Artemis.UI"
|
||||
x:Class="Artemis.UI.Windows.App">
|
||||
<Application.DataTemplates>
|
||||
<ui:ViewLocator/>
|
||||
</Application.DataTemplates>
|
||||
|
||||
<Application.Styles>
|
||||
<StyleInclude Source="avares://Artemis.UI/Styles/Artemis.axaml" />
|
||||
</Application.Styles>
|
||||
</Application>
|
||||
@@ -0,0 +1,47 @@
|
||||
using Artemis.Core.Services;
|
||||
using Artemis.UI.Shared.Providers;
|
||||
using Artemis.UI.Windows.Ninject;
|
||||
using Artemis.UI.Windows.Providers;
|
||||
using Artemis.UI.Windows.Providers.Input;
|
||||
using Avalonia;
|
||||
using Avalonia.Controls.ApplicationLifetimes;
|
||||
using Avalonia.Markup.Xaml;
|
||||
using Avalonia.Threading;
|
||||
using Ninject;
|
||||
using ReactiveUI;
|
||||
|
||||
namespace Artemis.UI.Windows
|
||||
{
|
||||
public class App : Application
|
||||
{
|
||||
public override void Initialize()
|
||||
{
|
||||
_kernel = ArtemisBootstrapper.Bootstrap(this, new WindowsModule());
|
||||
RxApp.MainThreadScheduler = AvaloniaScheduler.Instance;
|
||||
AvaloniaXamlLoader.Load(this);
|
||||
}
|
||||
|
||||
public override void OnFrameworkInitializationCompleted()
|
||||
{
|
||||
ArtemisBootstrapper.Initialize();
|
||||
|
||||
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
|
||||
{
|
||||
_applicationStateManager = new ApplicationStateManager(_kernel!, desktop.Args);
|
||||
RegisterProviders(_kernel!);
|
||||
}
|
||||
}
|
||||
|
||||
private void RegisterProviders(StandardKernel standardKernel)
|
||||
{
|
||||
IInputService inputService = standardKernel.Get<IInputService>();
|
||||
inputService.AddInputProvider(standardKernel.Get<WindowsInputProvider>());
|
||||
}
|
||||
|
||||
// ReSharper disable NotAccessedField.Local
|
||||
private StandardKernel? _kernel;
|
||||
|
||||
private ApplicationStateManager? _applicationStateManager;
|
||||
// ReSharper restore NotAccessedField.Local
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Security.Principal;
|
||||
using System.Threading;
|
||||
using Artemis.Core;
|
||||
using Artemis.Core.Services;
|
||||
using Artemis.UI.Shared.Services.Interfaces;
|
||||
using Artemis.UI.Windows.Utilities;
|
||||
using Avalonia;
|
||||
using Avalonia.Controls.ApplicationLifetimes;
|
||||
using Avalonia.Threading;
|
||||
using Ninject;
|
||||
|
||||
namespace Artemis.UI.Windows
|
||||
{
|
||||
public class ApplicationStateManager
|
||||
{
|
||||
private readonly IWindowService _windowService;
|
||||
|
||||
// ReSharper disable once NotAccessedField.Local - Kept in scope to ensure it does not get released
|
||||
private Mutex? _artemisMutex;
|
||||
|
||||
public ApplicationStateManager(IKernel kernel, string[] startupArguments)
|
||||
{
|
||||
_windowService = kernel.Get<IWindowService>();
|
||||
StartupArguments = startupArguments;
|
||||
IsElevated = new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator);
|
||||
|
||||
Core.Utilities.ShutdownRequested += UtilitiesOnShutdownRequested;
|
||||
Core.Utilities.RestartRequested += UtilitiesOnRestartRequested;
|
||||
|
||||
// On Windows shutdown dispose the kernel just so device providers get a chance to clean up
|
||||
if (Application.Current?.ApplicationLifetime is IControlledApplicationLifetime controlledApplicationLifetime)
|
||||
{
|
||||
controlledApplicationLifetime.Exit += (_, _) =>
|
||||
{
|
||||
RunForcedShutdownIfEnabled();
|
||||
|
||||
// Dispose plugins before disposing the kernel because plugins might access services during dispose
|
||||
kernel.Get<IPluginManagementService>().Dispose();
|
||||
kernel.Dispose();
|
||||
};
|
||||
}
|
||||
|
||||
// Inform the Core about elevation status
|
||||
kernel.Get<ICoreService>().IsElevated = IsElevated;
|
||||
}
|
||||
|
||||
public string[] StartupArguments { get; }
|
||||
public bool IsElevated { get; }
|
||||
|
||||
public bool FocusExistingInstance()
|
||||
{
|
||||
_artemisMutex = new Mutex(true, "Artemis-3c24b502-64e6-4587-84bf-9072970e535f", out bool createdNew);
|
||||
if (createdNew)
|
||||
return false;
|
||||
|
||||
return RemoteFocus();
|
||||
}
|
||||
|
||||
public void DisplayException(Exception e)
|
||||
{
|
||||
try
|
||||
{
|
||||
_windowService.ShowExceptionDialog("An unhandled exception occured", e);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// ignored, we tried
|
||||
}
|
||||
}
|
||||
|
||||
private bool RemoteFocus()
|
||||
{
|
||||
// At this point we cannot read the database yet to retrieve the web server port.
|
||||
// Instead use the method external applications should use as well.
|
||||
if (!File.Exists(Path.Combine(Constants.DataFolder, "webserver.txt")))
|
||||
{
|
||||
KillOtherInstances();
|
||||
return false;
|
||||
}
|
||||
|
||||
string url = File.ReadAllText(Path.Combine(Constants.DataFolder, "webserver.txt"));
|
||||
using HttpClient client = new();
|
||||
try
|
||||
{
|
||||
CancellationTokenSource cts = new();
|
||||
cts.CancelAfter(2000);
|
||||
|
||||
HttpResponseMessage httpResponseMessage = client.Send(new HttpRequestMessage(HttpMethod.Post, url + "remote/bring-to-foreground"), cts.Token);
|
||||
httpResponseMessage.EnsureSuccessStatusCode();
|
||||
return true;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
KillOtherInstances();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private void KillOtherInstances()
|
||||
{
|
||||
// Kill everything else heh
|
||||
List<Process> processes = Process.GetProcessesByName("Artemis.UI").Where(p => p.Id != Process.GetCurrentProcess().Id).ToList();
|
||||
foreach (Process process in processes)
|
||||
{
|
||||
try
|
||||
{
|
||||
process.Kill(true);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
// ignored
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void UtilitiesOnRestartRequested(object? sender, RestartEventArgs e)
|
||||
{
|
||||
List<string> argsList = new();
|
||||
argsList.AddRange(StartupArguments);
|
||||
if (e.ExtraArgs != null)
|
||||
argsList.AddRange(e.ExtraArgs.Except(argsList));
|
||||
string args = argsList.Any() ? "-ArgumentList " + string.Join(',', argsList) : "";
|
||||
string command =
|
||||
$"-Command \"& {{Start-Sleep -Milliseconds {(int) e.Delay.TotalMilliseconds}; " +
|
||||
"(Get-Process 'Artemis.UI').kill(); " +
|
||||
$"Start-Process -FilePath '{Constants.ExecutablePath}' -WorkingDirectory '{Constants.ApplicationFolder}' {args}}}\"";
|
||||
// Elevated always runs with RunAs
|
||||
if (e.Elevate)
|
||||
{
|
||||
ProcessStartInfo info = new()
|
||||
{
|
||||
Arguments = command.Replace("}\"", " -Verb RunAs}\""),
|
||||
WindowStyle = ProcessWindowStyle.Hidden,
|
||||
CreateNoWindow = true,
|
||||
FileName = "PowerShell.exe"
|
||||
};
|
||||
Process.Start(info);
|
||||
}
|
||||
// Non-elevated runs regularly if currently not elevated
|
||||
else if (!IsElevated)
|
||||
{
|
||||
ProcessStartInfo info = new()
|
||||
{
|
||||
Arguments = command,
|
||||
WindowStyle = ProcessWindowStyle.Hidden,
|
||||
CreateNoWindow = true,
|
||||
FileName = "PowerShell.exe"
|
||||
};
|
||||
Process.Start(info);
|
||||
}
|
||||
// Non-elevated runs via a utility method is currently elevated (de-elevating is hacky)
|
||||
else
|
||||
{
|
||||
string powerShell = Path.Combine(Environment.SystemDirectory, "WindowsPowerShell", "v1.0", "powershell.exe");
|
||||
ProcessUtilities.RunAsDesktopUser(powerShell, command, true);
|
||||
}
|
||||
|
||||
// Lets try a graceful shutdown, PowerShell will kill if needed
|
||||
if (Application.Current?.ApplicationLifetime is IControlledApplicationLifetime controlledApplicationLifetime)
|
||||
Dispatcher.UIThread.Post(() => controlledApplicationLifetime.Shutdown());
|
||||
}
|
||||
|
||||
private void UtilitiesOnShutdownRequested(object? sender, EventArgs e)
|
||||
{
|
||||
// Use PowerShell to kill the process after 8 sec just in case
|
||||
RunForcedShutdownIfEnabled();
|
||||
|
||||
if (Application.Current?.ApplicationLifetime is IControlledApplicationLifetime controlledApplicationLifetime)
|
||||
Dispatcher.UIThread.Post(() => controlledApplicationLifetime.Shutdown());
|
||||
}
|
||||
|
||||
private void RunForcedShutdownIfEnabled()
|
||||
{
|
||||
if (StartupArguments.Contains("--disable-forced-shutdown"))
|
||||
return;
|
||||
|
||||
ProcessStartInfo info = new()
|
||||
{
|
||||
Arguments = "-Command \"& {Start-Sleep -s 8; (Get-Process -Id " + Process.GetCurrentProcess().Id + ").kill()}",
|
||||
WindowStyle = ProcessWindowStyle.Hidden,
|
||||
CreateNoWindow = true,
|
||||
FileName = "PowerShell.exe"
|
||||
};
|
||||
Process.Start(info);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<OutputType>WinExe</OutputType>
|
||||
<TargetFramework>net6.0-windows</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<PlatformTarget>x64</PlatformTarget>
|
||||
<Platforms>x64</Platforms>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<AvaloniaResource Include="Assets\**" />
|
||||
<None Remove=".gitignore" />
|
||||
<None Remove="Assets\Cursors\aero_crosshair.cur" />
|
||||
<None Remove="Assets\Cursors\aero_crosshair_minus.cur" />
|
||||
<None Remove="Assets\Cursors\aero_crosshair_plus.cur" />
|
||||
<None Remove="Assets\Cursors\aero_drag.cur" />
|
||||
<None Remove="Assets\Cursors\aero_drag_ew.cur" />
|
||||
<None Remove="Assets\Cursors\aero_fill.cur" />
|
||||
<None Remove="Assets\Cursors\aero_pen_min.cur" />
|
||||
<None Remove="Assets\Cursors\aero_pen_plus.cur" />
|
||||
<None Remove="Assets\Cursors\aero_rotate.cur" />
|
||||
<None Remove="Assets\Cursors\aero_rotate_bl.cur" />
|
||||
<None Remove="Assets\Cursors\aero_rotate_br.cur" />
|
||||
<None Remove="Assets\Cursors\aero_rotate_tl.cur" />
|
||||
<None Remove="Assets\Cursors\aero_rotate_tr.cur" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Avalonia" Version="0.10.13" />
|
||||
<PackageReference Include="Avalonia.Desktop" Version="0.10.13" />
|
||||
<!--Condition below is needed to remove Avalonia.Diagnostics package from build output in Release configuration.-->
|
||||
<PackageReference Condition="'$(Configuration)' == 'Debug'" Include="Avalonia.Diagnostics" Version="0.10.13" />
|
||||
<PackageReference Include="Avalonia.ReactiveUI" Version="0.10.13" />
|
||||
<PackageReference Include="Avalonia.Win32" Version="0.10.13" />
|
||||
<PackageReference Include="Microsoft.Win32" Version="2.0.1" />
|
||||
<PackageReference Include="RawInput.Sharp" Version="0.0.4" />
|
||||
<PackageReference Include="ReactiveUI" Version="17.1.50" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Artemis.Core\Artemis.Core.csproj" />
|
||||
<ProjectReference Include="..\Artemis.UI\Artemis.UI.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
|
After Width: | Height: | Size: 347 B |
|
After Width: | Height: | Size: 356 B |
|
After Width: | Height: | Size: 369 B |
|
After Width: | Height: | Size: 627 B |
|
After Width: | Height: | Size: 1.1 KiB |
|
After Width: | Height: | Size: 460 B |
|
After Width: | Height: | Size: 472 B |
|
After Width: | Height: | Size: 825 B |
|
After Width: | Height: | Size: 673 B |
|
After Width: | Height: | Size: 678 B |
|
After Width: | Height: | Size: 671 B |
|
After Width: | Height: | Size: 669 B |
|
After Width: | Height: | Size: 172 KiB |
@@ -0,0 +1,18 @@
|
||||
using Artemis.UI.Shared.Providers;
|
||||
using Artemis.UI.Windows.Providers;
|
||||
using Ninject.Modules;
|
||||
|
||||
namespace Artemis.UI.Windows.Ninject;
|
||||
|
||||
public class WindowsModule : NinjectModule
|
||||
{
|
||||
#region Overrides of NinjectModule
|
||||
|
||||
/// <inheritdoc />
|
||||
public override void Load()
|
||||
{
|
||||
Kernel!.Bind<ICursorProvider>().To<CursorProvider>().InSingletonScope();
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
using System;
|
||||
using Avalonia;
|
||||
using Avalonia.ReactiveUI;
|
||||
|
||||
namespace Artemis.UI.Windows
|
||||
{
|
||||
internal class Program
|
||||
{
|
||||
// Initialization code. Don't use any Avalonia, third-party APIs or any
|
||||
// SynchronizationContext-reliant code before AppMain is called: things aren't initialized
|
||||
// yet and stuff might break.
|
||||
[STAThread]
|
||||
public static void Main(string[] args)
|
||||
{
|
||||
BuildAvaloniaApp().StartWithClassicDesktopLifetime(args);
|
||||
}
|
||||
|
||||
// Avalonia configuration, don't remove; also used by visual designer.
|
||||
public static AppBuilder BuildAvaloniaApp()
|
||||
{
|
||||
return AppBuilder.Configure<App>().UsePlatformDetect().LogToTrace().UseReactiveUI();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"profiles": {
|
||||
"Artemis.UI.Windows": {
|
||||
"commandName": "Project",
|
||||
"commandLineArgs": "--force-elevation --disable-forced-shutdown --pcmr"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
using System;
|
||||
using Artemis.UI.Shared.Providers;
|
||||
using Avalonia;
|
||||
using Avalonia.Input;
|
||||
using Avalonia.Media.Imaging;
|
||||
using Avalonia.Platform;
|
||||
|
||||
namespace Artemis.UI.Windows.Providers;
|
||||
|
||||
public class CursorProvider : ICursorProvider
|
||||
{
|
||||
public CursorProvider(IAssetLoader assetLoader)
|
||||
{
|
||||
Rotate = new Cursor(new Bitmap(assetLoader.Open(new Uri("avares://Artemis.UI.Windows/Assets/Cursors/aero_rotate.png"))), new PixelPoint(21, 10));
|
||||
Drag = new Cursor(new Bitmap(assetLoader.Open(new Uri("avares://Artemis.UI.Windows/Assets/Cursors/aero_drag.png"))), new PixelPoint(11, 3));
|
||||
DragHorizontal = new Cursor(new Bitmap(assetLoader.Open(new Uri("avares://Artemis.UI.Windows/Assets/Cursors/aero_drag_horizontal.png"))), new PixelPoint(16, 5));
|
||||
}
|
||||
|
||||
public Cursor Rotate { get; }
|
||||
public Cursor Drag { get; }
|
||||
public Cursor DragHorizontal { get; }
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
using System;
|
||||
using Avalonia.Win32;
|
||||
|
||||
namespace Artemis.UI.Windows.Providers.Input
|
||||
{
|
||||
public class SpongeWindow : WindowImpl
|
||||
{
|
||||
#region Overrides of WindowImpl
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override IntPtr WndProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam)
|
||||
{
|
||||
OnWndProcCalled(new SpongeWindowEventArgs(hWnd, msg, wParam, lParam));
|
||||
return base.WndProc(hWnd, msg, wParam, lParam);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
public event EventHandler<SpongeWindowEventArgs>? WndProcCalled;
|
||||
|
||||
protected virtual void OnWndProcCalled(SpongeWindowEventArgs e)
|
||||
{
|
||||
WndProcCalled?.Invoke(this, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
using System;
|
||||
|
||||
namespace Artemis.UI.Windows.Providers.Input
|
||||
{
|
||||
public class SpongeWindowEventArgs : EventArgs
|
||||
{
|
||||
public IntPtr HWnd { get; }
|
||||
public uint Msg { get; }
|
||||
public IntPtr WParam { get; }
|
||||
public IntPtr LParam { get; }
|
||||
|
||||
public SpongeWindowEventArgs(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam)
|
||||
{
|
||||
HWnd = hWnd;
|
||||
Msg = msg;
|
||||
WParam = wParam;
|
||||
LParam = lParam;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,283 @@
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Timers;
|
||||
using Artemis.Core;
|
||||
using Artemis.Core.Services;
|
||||
using Artemis.UI.Windows.Utilities;
|
||||
using Linearstar.Windows.RawInput;
|
||||
using Linearstar.Windows.RawInput.Native;
|
||||
using Serilog;
|
||||
using MouseButton = Artemis.Core.Services.MouseButton;
|
||||
|
||||
namespace Artemis.UI.Windows.Providers.Input
|
||||
{
|
||||
public class WindowsInputProvider : InputProvider
|
||||
{
|
||||
private const int WM_INPUT = 0x00FF;
|
||||
|
||||
private readonly IInputService _inputService;
|
||||
private readonly ILogger _logger;
|
||||
private DateTime _lastMouseUpdate;
|
||||
private int _lastProcessId;
|
||||
private SpongeWindow _sponge;
|
||||
private readonly Timer _taskManagerTimer;
|
||||
|
||||
public WindowsInputProvider(ILogger logger, IInputService inputService)
|
||||
{
|
||||
_logger = logger;
|
||||
_inputService = inputService;
|
||||
|
||||
_sponge = new SpongeWindow();
|
||||
_sponge.WndProcCalled += SpongeOnWndProcCalled;
|
||||
|
||||
_taskManagerTimer = new Timer(500);
|
||||
_taskManagerTimer.Elapsed += TaskManagerTimerOnElapsed;
|
||||
_taskManagerTimer.Start();
|
||||
|
||||
RawInputDevice.RegisterDevice(HidUsageAndPage.Keyboard, RawInputDeviceFlags.InputSink, _sponge.Handle.Handle);
|
||||
RawInputDevice.RegisterDevice(HidUsageAndPage.Mouse, RawInputDeviceFlags.InputSink, _sponge.Handle.Handle);
|
||||
}
|
||||
|
||||
|
||||
#region Overrides of InputProvider
|
||||
|
||||
/// <inheritdoc />
|
||||
public override void OnKeyboardToggleStatusRequested()
|
||||
{
|
||||
UpdateToggleStatus();
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region IDisposable
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing)
|
||||
{
|
||||
_sponge.Dispose();
|
||||
_taskManagerTimer.Dispose();
|
||||
}
|
||||
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
private void SpongeOnWndProcCalled(object? sender, SpongeWindowEventArgs message)
|
||||
{
|
||||
if (message.Msg != WM_INPUT)
|
||||
return;
|
||||
|
||||
RawInputData data = RawInputData.FromHandle(message.LParam);
|
||||
switch (data)
|
||||
{
|
||||
case RawInputMouseData mouse:
|
||||
HandleMouseData(data, mouse);
|
||||
break;
|
||||
case RawInputKeyboardData keyboard:
|
||||
HandleKeyboardData(data, keyboard);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private void TaskManagerTimerOnElapsed(object sender, ElapsedEventArgs e)
|
||||
{
|
||||
int processId = WindowUtilities.GetActiveProcessId();
|
||||
if (processId == _lastProcessId)
|
||||
return;
|
||||
|
||||
_lastProcessId = processId;
|
||||
|
||||
// If task manager has focus then we can't track keys properly, release everything to avoid them getting stuck
|
||||
// Same goes for Idle which is what you get when you press Ctrl+Alt+Del
|
||||
Process active = Process.GetProcessById(processId);
|
||||
if (active?.ProcessName == "Taskmgr" || active?.ProcessName == "Idle")
|
||||
_inputService.ReleaseAll();
|
||||
}
|
||||
|
||||
#region Keyboard
|
||||
|
||||
private void HandleKeyboardData(RawInputData data, RawInputKeyboardData keyboardData)
|
||||
{
|
||||
KeyboardKey key = InputUtilities.KeyFromVirtualKey(keyboardData.Keyboard.VirutalKey);
|
||||
// Debug.WriteLine($"VK: {key} ({keyboardData.Keyboard.VirutalKey}), Flags: {keyboardData.Keyboard.Flags}, Scan code: {keyboardData.Keyboard.ScanCode}");
|
||||
|
||||
// Sometimes we get double hits and they resolve to None, ignore those
|
||||
if (key == KeyboardKey.None)
|
||||
return;
|
||||
|
||||
// Right alt triggers LeftCtrl with a different scan code for some reason, ignore those
|
||||
if (key == KeyboardKey.LeftCtrl && keyboardData.Keyboard.ScanCode == 56)
|
||||
return;
|
||||
|
||||
string? identifier = data.Device?.DevicePath;
|
||||
|
||||
// Let the core know there is an identifier so it can store new identifications if applicable
|
||||
if (identifier != null)
|
||||
OnIdentifierReceived(identifier, InputDeviceType.Keyboard);
|
||||
|
||||
ArtemisDevice? device = null;
|
||||
if (identifier != null)
|
||||
try
|
||||
{
|
||||
device = _inputService.GetDeviceByIdentifier(this, identifier, InputDeviceType.Keyboard);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
_logger.Warning(e, "Failed to retrieve input device by its identifier");
|
||||
}
|
||||
|
||||
// Duplicate keys with different positions can be identified by the LeftKey flag (even though its set of the key that's physically on the right)
|
||||
if (keyboardData.Keyboard.Flags == RawKeyboardFlags.KeyE0 || keyboardData.Keyboard.Flags == (RawKeyboardFlags.KeyE0 | RawKeyboardFlags.Up))
|
||||
{
|
||||
if (key == KeyboardKey.Enter)
|
||||
key = KeyboardKey.NumPadEnter;
|
||||
if (key == KeyboardKey.LeftCtrl)
|
||||
key = KeyboardKey.RightCtrl;
|
||||
if (key == KeyboardKey.LeftAlt)
|
||||
key = KeyboardKey.RightAlt;
|
||||
}
|
||||
|
||||
if (key == KeyboardKey.LeftShift && keyboardData.Keyboard.ScanCode == 54)
|
||||
key = KeyboardKey.RightShift;
|
||||
|
||||
bool isDown = keyboardData.Keyboard.Flags != RawKeyboardFlags.Up &&
|
||||
keyboardData.Keyboard.Flags != (RawKeyboardFlags.Up | RawKeyboardFlags.KeyE0) &&
|
||||
keyboardData.Keyboard.Flags != (RawKeyboardFlags.Up | RawKeyboardFlags.KeyE1);
|
||||
|
||||
OnKeyboardDataReceived(device, key, isDown);
|
||||
UpdateToggleStatus();
|
||||
}
|
||||
|
||||
private void UpdateToggleStatus()
|
||||
{
|
||||
OnKeyboardToggleStatusReceived(new KeyboardToggleStatus(
|
||||
InputUtilities.IsKeyToggled(KeyboardKey.NumLock),
|
||||
InputUtilities.IsKeyToggled(KeyboardKey.CapsLock),
|
||||
InputUtilities.IsKeyToggled(KeyboardKey.Scroll)
|
||||
));
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Mouse
|
||||
|
||||
private int _mouseDeltaX;
|
||||
private int _mouseDeltaY;
|
||||
|
||||
private void HandleMouseData(RawInputData data, RawInputMouseData mouseData)
|
||||
{
|
||||
// Only submit mouse movement 25 times per second but increment the delta
|
||||
// This can create a small inaccuracy of course, but Artemis is not a shooter :')
|
||||
if (mouseData.Mouse.Buttons == RawMouseButtonFlags.None)
|
||||
{
|
||||
_mouseDeltaX += mouseData.Mouse.LastX;
|
||||
_mouseDeltaY += mouseData.Mouse.LastY;
|
||||
if (DateTime.Now - _lastMouseUpdate < TimeSpan.FromMilliseconds(40))
|
||||
return;
|
||||
}
|
||||
|
||||
ArtemisDevice? device = null;
|
||||
string? identifier = data.Device?.DevicePath;
|
||||
if (identifier != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
device = _inputService.GetDeviceByIdentifier(this, identifier, InputDeviceType.Mouse);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
_logger.Warning(e, "Failed to retrieve input device by its identifier");
|
||||
}
|
||||
}
|
||||
|
||||
// Debug.WriteLine($"Buttons: {mouseData.Mouse.Buttons}, Data: {mouseData.Mouse.ButtonData}, Flags: {mouseData.Mouse.Flags}, XY: {mouseData.Mouse.LastX},{mouseData.Mouse.LastY}");
|
||||
|
||||
// Movement
|
||||
if (mouseData.Mouse.Buttons == RawMouseButtonFlags.None)
|
||||
{
|
||||
Win32Point cursorPosition = GetCursorPosition();
|
||||
OnMouseMoveDataReceived(device, cursorPosition.X, cursorPosition.Y, _mouseDeltaX, _mouseDeltaY);
|
||||
_mouseDeltaX = 0;
|
||||
_mouseDeltaY = 0;
|
||||
_lastMouseUpdate = DateTime.Now;
|
||||
return;
|
||||
}
|
||||
|
||||
// Now we know its not movement, let the core know there is an identifier so it can store new identifications if applicable
|
||||
if (identifier != null)
|
||||
OnIdentifierReceived(identifier, InputDeviceType.Mouse);
|
||||
|
||||
// Scrolling
|
||||
if (mouseData.Mouse.ButtonData != 0)
|
||||
{
|
||||
if (mouseData.Mouse.Buttons == RawMouseButtonFlags.MouseWheel)
|
||||
OnMouseScrollDataReceived(device, MouseScrollDirection.Vertical, mouseData.Mouse.ButtonData);
|
||||
else if (mouseData.Mouse.Buttons == RawMouseButtonFlags.MouseHorizontalWheel)
|
||||
OnMouseScrollDataReceived(device, MouseScrollDirection.Horizontal, mouseData.Mouse.ButtonData);
|
||||
return;
|
||||
}
|
||||
|
||||
// Button presses
|
||||
MouseButton button = MouseButton.Left;
|
||||
bool isDown = false;
|
||||
|
||||
// Left
|
||||
if (DetermineMouseButton(mouseData, RawMouseButtonFlags.LeftButtonDown, RawMouseButtonFlags.LeftButtonUp, ref isDown))
|
||||
button = MouseButton.Left;
|
||||
// Middle
|
||||
else if (DetermineMouseButton(mouseData, RawMouseButtonFlags.MiddleButtonDown, RawMouseButtonFlags.MiddleButtonUp, ref isDown))
|
||||
button = MouseButton.Middle;
|
||||
// Right
|
||||
else if (DetermineMouseButton(mouseData, RawMouseButtonFlags.RightButtonDown, RawMouseButtonFlags.RightButtonUp, ref isDown))
|
||||
button = MouseButton.Right;
|
||||
// Button 4
|
||||
else if (DetermineMouseButton(mouseData, RawMouseButtonFlags.Button4Down, RawMouseButtonFlags.Button4Up, ref isDown))
|
||||
button = MouseButton.Button4;
|
||||
else if (DetermineMouseButton(mouseData, RawMouseButtonFlags.Button5Down, RawMouseButtonFlags.Button5Up, ref isDown))
|
||||
button = MouseButton.Button5;
|
||||
|
||||
OnMouseButtonDataReceived(device, button, isDown);
|
||||
}
|
||||
|
||||
private bool DetermineMouseButton(RawInputMouseData data, RawMouseButtonFlags downButton, RawMouseButtonFlags upButton, ref bool isDown)
|
||||
{
|
||||
if (data.Mouse.Buttons == downButton || data.Mouse.Buttons == upButton)
|
||||
{
|
||||
isDown = data.Mouse.Buttons == downButton;
|
||||
return true;
|
||||
}
|
||||
|
||||
isDown = false;
|
||||
return false;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Native
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
private static extern bool GetCursorPos(ref Win32Point pt);
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct Win32Point
|
||||
{
|
||||
public readonly int X;
|
||||
public readonly int Y;
|
||||
}
|
||||
|
||||
private static Win32Point GetCursorPosition()
|
||||
{
|
||||
Win32Point w32Mouse = new();
|
||||
GetCursorPos(ref w32Mouse);
|
||||
|
||||
return w32Mouse;
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace Artemis.UI.Windows.Utilities
|
||||
{
|
||||
public static class ProcessUtilities
|
||||
{
|
||||
public static Process? RunAsDesktopUser(string fileName, string arguments, bool hideWindow)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(fileName))
|
||||
throw new ArgumentException("Value cannot be null or whitespace.", nameof(fileName));
|
||||
|
||||
// To start process as shell user you will need to carry out these steps:
|
||||
// 1. Enable the SeIncreaseQuotaPrivilege in your current token
|
||||
// 2. Get an HWND representing the desktop shell (GetShellWindow)
|
||||
// 3. Get the Process ID(PID) of the process associated with that window(GetWindowThreadProcessId)
|
||||
// 4. Open that process(OpenProcess)
|
||||
// 5. Get the access token from that process (OpenProcessToken)
|
||||
// 6. Make a primary token with that token(DuplicateTokenEx)
|
||||
// 7. Start the new process with that primary token(CreateProcessWithTokenW)
|
||||
|
||||
IntPtr hProcessToken = IntPtr.Zero;
|
||||
// Enable SeIncreaseQuotaPrivilege in this process. (This won't work if current process is not elevated.)
|
||||
try
|
||||
{
|
||||
IntPtr process = GetCurrentProcess();
|
||||
if (!OpenProcessToken(process, 0x0020, ref hProcessToken))
|
||||
return null;
|
||||
|
||||
TOKEN_PRIVILEGES tkp = new()
|
||||
{
|
||||
PrivilegeCount = 1,
|
||||
Privileges = new LUID_AND_ATTRIBUTES[1]
|
||||
};
|
||||
|
||||
if (!LookupPrivilegeValue(null, "SeIncreaseQuotaPrivilege", ref tkp.Privileges[0].Luid))
|
||||
return null;
|
||||
|
||||
tkp.Privileges[0].Attributes = 0x00000002;
|
||||
|
||||
if (!AdjustTokenPrivileges(hProcessToken, false, ref tkp, 0, IntPtr.Zero, IntPtr.Zero))
|
||||
return null;
|
||||
}
|
||||
finally
|
||||
{
|
||||
CloseHandle(hProcessToken);
|
||||
}
|
||||
|
||||
// Get an HWND representing the desktop shell.
|
||||
// CAVEATS: This will fail if the shell is not running (crashed or terminated), or the default shell has been
|
||||
// replaced with a custom shell. This also won't return what you probably want if Explorer has been terminated and
|
||||
// restarted elevated.
|
||||
IntPtr hwnd = GetShellWindow();
|
||||
if (hwnd == IntPtr.Zero)
|
||||
return null;
|
||||
|
||||
IntPtr hShellProcess = IntPtr.Zero;
|
||||
IntPtr hShellProcessToken = IntPtr.Zero;
|
||||
IntPtr hPrimaryToken = IntPtr.Zero;
|
||||
try
|
||||
{
|
||||
// Get the PID of the desktop shell process.
|
||||
uint dwPID;
|
||||
if (GetWindowThreadProcessId(hwnd, out dwPID) == 0)
|
||||
return null;
|
||||
|
||||
// Open the desktop shell process in order to query it (get the token)
|
||||
hShellProcess = OpenProcess(ProcessAccessFlags.QueryInformation, false, dwPID);
|
||||
if (hShellProcess == IntPtr.Zero)
|
||||
return null;
|
||||
|
||||
// Get the process token of the desktop shell.
|
||||
if (!OpenProcessToken(hShellProcess, 0x0002, ref hShellProcessToken))
|
||||
return null;
|
||||
|
||||
uint dwTokenRights = 395U;
|
||||
|
||||
// Duplicate the shell's process token to get a primary token.
|
||||
// Based on experimentation, this is the minimal set of rights required for CreateProcessWithTokenW (contrary to current documentation).
|
||||
if (!DuplicateTokenEx(hShellProcessToken, dwTokenRights, IntPtr.Zero, SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, TOKEN_TYPE.TokenPrimary, out hPrimaryToken))
|
||||
return null;
|
||||
|
||||
// Start the target process with the new token.
|
||||
STARTUPINFO si = new();
|
||||
if (hideWindow)
|
||||
{
|
||||
si.dwFlags = 0x00000001;
|
||||
si.wShowWindow = 0;
|
||||
}
|
||||
|
||||
PROCESS_INFORMATION pi = new();
|
||||
if (!CreateProcessWithTokenW(hPrimaryToken, 0, fileName, $"\"{fileName}\" {arguments}", 0, IntPtr.Zero, Path.GetDirectoryName(fileName)!, ref si, out pi))
|
||||
{
|
||||
// Get the last error and display it.
|
||||
int error = Marshal.GetLastWin32Error();
|
||||
return null;
|
||||
}
|
||||
|
||||
return Process.GetProcessById(pi.dwProcessId);
|
||||
}
|
||||
finally
|
||||
{
|
||||
CloseHandle(hShellProcessToken);
|
||||
CloseHandle(hPrimaryToken);
|
||||
CloseHandle(hShellProcess);
|
||||
}
|
||||
}
|
||||
|
||||
#region Interop
|
||||
|
||||
private struct TOKEN_PRIVILEGES
|
||||
{
|
||||
public uint PrivilegeCount;
|
||||
|
||||
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
|
||||
public LUID_AND_ATTRIBUTES[] Privileges;
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential, Pack = 4)]
|
||||
private struct LUID_AND_ATTRIBUTES
|
||||
{
|
||||
public LUID Luid;
|
||||
public uint Attributes;
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct LUID
|
||||
{
|
||||
public readonly uint LowPart;
|
||||
public readonly int HighPart;
|
||||
}
|
||||
|
||||
[Flags]
|
||||
private enum ProcessAccessFlags : uint
|
||||
{
|
||||
All = 0x001F0FFF,
|
||||
Terminate = 0x00000001,
|
||||
CreateThread = 0x00000002,
|
||||
VirtualMemoryOperation = 0x00000008,
|
||||
VirtualMemoryRead = 0x00000010,
|
||||
VirtualMemoryWrite = 0x00000020,
|
||||
DuplicateHandle = 0x00000040,
|
||||
CreateProcess = 0x000000080,
|
||||
SetQuota = 0x00000100,
|
||||
SetInformation = 0x00000200,
|
||||
QueryInformation = 0x00000400,
|
||||
QueryLimitedInformation = 0x00001000,
|
||||
Synchronize = 0x00100000
|
||||
}
|
||||
|
||||
private enum SECURITY_IMPERSONATION_LEVEL
|
||||
{
|
||||
SecurityAnonymous,
|
||||
SecurityIdentification,
|
||||
SecurityImpersonation,
|
||||
SecurityDelegation
|
||||
}
|
||||
|
||||
private enum TOKEN_TYPE
|
||||
{
|
||||
TokenPrimary = 1,
|
||||
TokenImpersonation
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct PROCESS_INFORMATION
|
||||
{
|
||||
public readonly IntPtr hProcess;
|
||||
public readonly IntPtr hThread;
|
||||
public readonly int dwProcessId;
|
||||
public readonly int dwThreadId;
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
|
||||
private struct STARTUPINFO
|
||||
{
|
||||
public readonly int cb;
|
||||
public readonly string lpReserved;
|
||||
public readonly string lpDesktop;
|
||||
public readonly string lpTitle;
|
||||
public readonly int dwX;
|
||||
public readonly int dwY;
|
||||
public readonly int dwXSize;
|
||||
public readonly int dwYSize;
|
||||
public readonly int dwXCountChars;
|
||||
public readonly int dwYCountChars;
|
||||
public readonly int dwFillAttribute;
|
||||
public int dwFlags;
|
||||
public short wShowWindow;
|
||||
public readonly short cbReserved2;
|
||||
public readonly IntPtr lpReserved2;
|
||||
public readonly IntPtr hStdInput;
|
||||
public readonly IntPtr hStdOutput;
|
||||
public readonly IntPtr hStdError;
|
||||
}
|
||||
|
||||
[DllImport("kernel32.dll", ExactSpelling = true)]
|
||||
private static extern IntPtr GetCurrentProcess();
|
||||
|
||||
[DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)]
|
||||
private static extern bool OpenProcessToken(IntPtr h, int acc, ref IntPtr phtok);
|
||||
|
||||
[DllImport("advapi32.dll", SetLastError = true)]
|
||||
private static extern bool LookupPrivilegeValue(string? host, string name, ref LUID pluid);
|
||||
|
||||
[DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)]
|
||||
private static extern bool AdjustTokenPrivileges(IntPtr htok, bool disall, ref TOKEN_PRIVILEGES newst, int len, IntPtr prev, IntPtr relen);
|
||||
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
private static extern bool CloseHandle(IntPtr hObject);
|
||||
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern IntPtr GetShellWindow();
|
||||
|
||||
[DllImport("user32.dll", SetLastError = true)]
|
||||
private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
|
||||
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
private static extern IntPtr OpenProcess(ProcessAccessFlags processAccess, bool bInheritHandle, uint processId);
|
||||
|
||||
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
|
||||
private static extern bool DuplicateTokenEx(IntPtr hExistingToken, uint dwDesiredAccess, IntPtr lpTokenAttributes, SECURITY_IMPERSONATION_LEVEL impersonationLevel, TOKEN_TYPE tokenType,
|
||||
out IntPtr phNewToken);
|
||||
|
||||
[DllImport("advapi32", SetLastError = true, CharSet = CharSet.Unicode)]
|
||||
private static extern bool CreateProcessWithTokenW(IntPtr hToken, int dwLogonFlags, string lpApplicationName, string lpCommandLine, int dwCreationFlags, IntPtr lpEnvironment,
|
||||
string lpCurrentDirectory, [In] ref STARTUPINFO lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation);
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace Artemis.UI.Windows.Utilities
|
||||
{
|
||||
public static class WindowUtilities
|
||||
{
|
||||
public static int GetActiveProcessId()
|
||||
{
|
||||
// Get foreground window handle
|
||||
IntPtr hWnd = GetForegroundWindow();
|
||||
|
||||
GetWindowThreadProcessId(hWnd, out uint processId);
|
||||
return (int) processId;
|
||||
}
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern IntPtr GetForegroundWindow();
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
|
||||
}
|
||||
}
|
||||