grabacr07 / virtualdesktop Goto Github PK
View Code? Open in Web Editor NEWC# wrapper for the Virtual Desktop API on Windows 11.
License: MIT License
C# wrapper for the Virtual Desktop API on Windows 11.
License: MIT License
I modified the MainWindow.xaml.cs like this:
public MainWindow()
{
this.InitializeComponent();
VirtualDesktop.CurrentChanged += VirtualDesktop_CurrentChanged;
}
private void VirtualDesktop_CurrentChanged(object sender, VirtualDesktopChangedEventArgs e)
{
Console.WriteLine("CurrentChanged");
}
The program crashes, however if I comment out the VirtualDesktop.CurrentChanged += VirtualDesktop_CurrentChanged;
it works.
Reason I'm trying this is because I'm testing the notifications on C++ code but there is a input lag if I register a notifications listener from C++. Also the printing does not register. I wonder if the notifications definition given in the Russian cyberforum (which is only reference I could find) is out dated?
Hello, I've wanted to ask if it's possible to run a program in another desktop so it runs kind of in background. Right now I'm using something like this:
proc.Start();
proc.WaitForInputIdle();
IntPtr handle = proc.MainWindowHandle;
handle.MoveToDesktop(desk);
I've almost reached wanted result but window still blinks for a split second which is annoying.
Thanks in advance, awesome work!
After upgrading my Windows 11 installation to the insider build below I get the following exception:
Edition Windows 11 Pro
Version 22H2
OS build 22598.200
Experience Windows Feature Experience Pack 1000.22598.200.0
System.Collections.Generic.KeyNotFoundException
HResult=0x80131577
Message=The given key 'IApplicationView' was not present in the dictionary.
Source=System.Private.CoreLib
StackTrace:
at System.ThrowHelper.ThrowKeyNotFoundException[T](T key)
at WindowsDesktop.Interop.ComInterfaceAssemblyBuilder.CreateAssembly()
at WindowsDesktop.Interop.ComInterfaceAssemblyBuilder.GetAssembly()
at WindowsDesktop.VirtualDesktop.InitializeCore()
at WindowsDesktop.VirtualDesktop.InitializeIfNeeded()
at WindowsDesktop.VirtualDesktop.get_Current()
Related issues:
When I start a new application (like Chrome) and ask for its desktop (via VirtualDesktop FromHwnd(IntPtr hWnd)), then I get the following exception:
{"Element not found. (Exception from HRESULT: 0x8002802B (TYPE_E_ELEMENTNOTFOUND))"}
If I click one the application that I just started and then call again "VirtualDesktop FromHwnd(IntPtr hWnd) " then I do get an exception and the function works well..
Any idea?
Thanks!
There are any method to create a 'desktop changed' event?
I want know when the user switch for a certain desktop.
If SynchronizationContext.Current
is null, VirtualDesktopProvider.Initialize
will throw an InvalidOperationException: 'The current SynchronizationContext may not be used as a TaskScheduler.'
at
VirtualDesktop/source/VirtualDesktop/VirtualDesktopProvider.cs
Lines 28 to 29 in a6aba70
This stops a blank console app from using VirtualDesktop.
Steps to reproduce:
VirtualDesktopProvider.Default.Initialize()
(or a method that calls it for you like VirtualDesktop.GetDesktops()
).Workaround:
Call SynchronizationContext.SetSynchronizationContext
first or use Initialize(TaskScheduler scheduler)
.
Is there a version for WinUI?
I'm not sure if this is possible, but I would like to build a list of which windows are pinned and which applications are pinned.
I am getting Virtual Desktop of each running process (by handles) by Using Windows APIs and following code snippet.
List<IntPtr> handles = GetWindowsHandles();
foreach (var hWnd in handles)
{
VirtualDesktop Virtual_Desktop = VirtualDesktop.FromHwnd(hWnd);
}
But when handle of Msedge and Notepad++ is passed to this method, Virtual Desktop is null.
If I start the example in a desktop app I get the following error:
foreach (var id in VirtualDesktop.GetDesktops().Select(x => x.Id)) <<<<<<<<<<<<< ! Error
{
}
System.NullReferenceException: "Der Objektverweis wurde nicht auf eine Objektinstanz festgelegt."
WinUI 3, .NET 6, Windows 10, I'm getting a bunch exceptions on app exit.
Is there something I need to call to exit properly?
Exception thrown at 0x00007FFF1F7B4F69 (KernelBase.dll) in App.exe: WinRT originate error - 0x800710DD : 'The WinUI Desktop Window object has already been closed.'.
onecore\com\combase\winrt\error\restrictederror.cpp(1016)\combase.dll!00007FFF1FCCC363: (caller: 00007FFF1FCD6049) ReturnHr(5) tid(1ad5c) 8007007E The specified module could not be found.
Exception thrown at 0x00007FFF1F7B4F69 (KernelBase.dll) in App.exe: WinRT originate error - 0x80000013 : 'The given object has already been closed / disposed and may no longer be used.'.
onecore\com\combase\winrt\error\restrictederror.cpp(1016)\combase.dll!00007FFF1FCCC363: (caller: 00007FFF1FCD6049) ReturnHr(6) tid(1ad5c) 8007007E The specified module could not be found.
Exception thrown at 0x00007FFF1F7B4F69 (KernelBase.dll) in App.exe: WinRT originate error - 0x80000013 : 'The given object has already been closed / disposed and may no longer be used.'.
onecore\com\combase\winrt\error\restrictederror.cpp(1016)\combase.dll!00007FFF1FCCC363: (caller: 00007FFF1FCD6049) ReturnHr(7) tid(1ad5c) 8007007E The specified module could not be found.
User reported a COMException during startup (my program is set to run at user log in from a schedule task).
Says it doesn't happen after a fresh install of Windows 10 Education edition but after a few restarts this exception occurs.
I'm attempting to use this library on Windows 10 with Visual Studio Community 2017 Version 15.4.2. I installed VirtualDesktop through NuGet:
PM> Install-Package VirtualDesktop -Version 2.0.0-beta3
I've copied the app.manifest file from the example project, and have verified in the csproj file that it's looking at the correct manifest file. I run the application in release mode, yet I get the System.NotSupportedException
.
Any idea what's wrong?
If I comment out the VirtualDesktopHelper.ThrowIfNotSupported()
calls, things work as expected.
See this registry entry:
Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Interface\{1841C6D7-4F9D-42C0-AF41-8747538F10E5}
In 1809 the value in config must be changed. There are still some other changes I'm exploring myself.
I get this Stack Trace by automatic crash report of my program that users VirtualDesktop
System.NotSupportedException: Specified method is not supported.
at WindowsDesktop.Interop.VirtualDesktopManagerInternal.GetInstance()
at WindowsDesktop.Interop.ComObjects.Initialize()
at WindowsDesktop.Interop.ComObjects.ExplorerRestartListenerWindow.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at System.Windows.Interop.HwndSource.PublicHooksFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
OSVersion: Microsoft Windows NT 10.0.21337.0
I don't get additional information to know what the user did to cause this but I would like to know how I can prevent the crash.
Hi,
When I use this library,In some case(console sofware and vsto--- i tried .net4.72 version that pulled in pull requests! ),always get error:"You must target Windows 10 or later in your 'app.manifest' and run without debugging." ,but i created a app.manifest file and target windows 10.
So the library only Can be used in wpf ? otherwise , I am wrong?
Anyone can help me?
As the title suggests, the methods are not recognized.
Good Job
Visual Studio 2015 throws this error:
Could not install package 'VirtualDesktop 1.0.3'. You are trying to install this package into a project that targets '.NETFramework,Version=v4.5.2', but the package does not contain any assembly references or content files that are compatible with that framework. For more information, contact the package author.
VirtualDesktopHelper.MoveToDesktop() fails because the Guid for IApplicationView in the version I have is 2929D253-6BF8-47A5-B229-3ED113C5B404. If I change to this Guid it works.
Settings says I have version 1511 Build 10586.545.
When I debug it is IVirtualDesktopManagerInternal10240 that is instantiated.
I considered fixing myself and submitting but wasn't sure how you would want to do it as I can't see how you can expose IApplicationView without wrapping it in your own class to make it work in all versions.
Please add include for .NET 7.0
(Works in wpf in csproj file)
<TargetFrameworks>net7.0-windows10.0.19041.0;net6.0-windows10.0.19041.0;net5.0-windows10.0.19041.0</TargetFrameworks>
<PropertyGroup Condition="'$(Configuration)|$(TargetFramework)|$(Platform)'=='Debug|net7.0-windows10.0.19041.0|AnyCPU'">
<NoWarn>1701;1702;1591</NoWarn>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(TargetFramework)|$(Platform)'=='Release|net7.0-windows10.0.19041.0|AnyCPU'">
<NoWarn>1701;1702;1591</NoWarn>
</PropertyGroup>`
I am trying to run the sample program, but the compiler is telling me that VirtualDesktopProvider
does not exist, so it cannot even compile VirtualDesktopProvider.Default.Initialize();
try
{
await VirtualDesktopProvider.Default.Initialize();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Failed to initialize.");
}
Has something changed?
Using the Showcase, it seems every(?) call to WindowsDesktop.Interop.ComObjects.ApplicationViewCollection.GetViewForHwnd() returns null. I am using Visual Studio 2017 on Windows 10 Build 17686 64-bit (this is the very latest Windows Insider build in the Fast Ring at the time of writing).
Calls I can confirm crash are "this window" and "foreground window" with "pin/unpin" or "pin/unpin (app)" as well as "foreground window" with any calls that moves a window other than self (I used notepad).
I haven't tried this with your library, but just reading your code you don't seem to check the HWND for being zero so I presume you have this bug / feature also.
I've tried this in the C++ and GetApplicationViewForHwnd(0)
crashes the explorer.exe, Twinui.dll more specifically.
Hi. First or all thanks for this library. It's easy to use and it works.
My users are reporting this error the first time they try to switch virtual desktops while running my program.
"Operation is not valid due to the current state of the object."
To give you context, for my main window I added a listener to your virtual desktop current changed event to move my main window to the new current virtual desktop.
Users report that after restarting the error never occurs again. However I was wondering if there is any way to solve the root cause of the error.
Here us a user's screenshot of the stack trace. Thanks.
https://cloud.githubusercontent.com/assets/2855069/12716357/c4432014-c8d7-11e5-9197-2660a4c1459a.png
Hi! Wonderful library, thanks for sharing it! I'm using it to switch desktops using hand gestures (via a Leap Motion). This library saved me a ton of research, I really appreciate it!
It would be nice if it were available on NuGet for ease of use and additional discoverability.
Hi there,
I have already seen "Desktop name is empty #65", but can somebody please explain me more in detail, why we cannot get the name of the desktops under Windows10.
I just upgraded my own project from .net framework to .net 6 and now the names are not available anymore.
With the (old) .net framework (4.72) repository of your VirtualDesktop it was possible and I liked to use it under Win10.
For the Wallpaper-Path I understand it, that's a newly feature and in my project I don't need this, but the VD-Name would be good.
Is there any way/workaround for this?
Regards
Rolf
Hi, i have a problem for create new Virtual Desktop.
I call this:
VirtualDesktop test = VirtualDesktop.Create();
And get:
...Chargé 'C:\Users\...\Desktop\...\...\...\...\bin\Debug\VirtualDesktop.dll'.
Exception levée : 'System.NullReferenceException' dans VirtualDesktop.dll
Hello,
Thanks for the library. This is great idea!
I tried the sample code:
var desktops = VirtualDesktop.GetDesktops();
// Get Virtual Desktop for specific window
var desktop = VirtualDesktop.FromHwnd(Process.GetCurrentProcess().MainWindowHandle);
It compiles but when it arrive to the VirtualDesktop.GetDesktops(); it throws an exception:
System.InvalidOperationException
HResult=0x80131509
Message=The current SynchronizationContext may not be used as a TaskScheduler.
Source=mscorlib
StackTrace:
at System.Threading.Tasks.SynchronizationContextTaskScheduler..ctor()
I'm using VS 2019 on Win 10....all latest version. I'm also using the latest version of your library
Thank you for your help
w.
I think this should recreate the com object if explorer restarts.
One can listen to explore restarts using this snippet:
HwndSource hwndSource;
uint explorerRestartMsg;
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
static extern uint RegisterWindowMessage(string lpProcName);
private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
if (msg == explorerRestartMsg)
{
MessageBox.Show("Explorer restart!");
}
return IntPtr.Zero;
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
hwndSource = HwndSource.FromHwnd(this.GetHandle());
hwndSource.AddHook(new HwndSourceHook(WndProc));
explorerRestartMsg = RegisterWindowMessage("TaskbarCreated");
}
One can get handle also without Window using WindowInteropHelper
HwndSource source = HwndSource.FromHwnd(new WindowInteropHelper(this).Handle);
source.AddHook(new HwndSourceHook(WndProc));
I think it suits for this library.
It would be neat if we could name or alias the virtual desktops.
Cannot run on Win11
If the last active window isn't in the target Virtual Desktop (the one we are switching to), the last window which had focus on the target Virtual Desktop starts flashing. This happened to me on version beta3.
Switching via Ctrl+Win+Arrow keys does not show the same behavior.
I tried using the desktop name from the current desktop and from the new desktop upon CurrentChanged
event but both return empty strings.
Hello,
I use all latest (windows 10 latest June 2020 update)
I have .net 4.8 and 4.72
Whe I run the application I got the following error:
'BindingFailure' : 'The assembly with display name 'Microsoft.CodeAnalysis' failed to load in the 'LoadFrom' binding context of the AppDomain with ID 1. The cause of the failure was: System.IO.FileLoadException: Could not load file or assembly 'Microsoft.CodeAnalysis, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)'
Could not load file or assembly 'Microsoft.CodeAnalysis, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
Any idea how I could solved this?
Thank you!
SylphyHorn と VirtualDesktop どちらに書けばいいのか悩んだので,とりあえずこちらに書いておきます。
Depending on how you use VirtualDesktop, apps add changed handler to the notification service twice and receive the same two notifications.
VirtualDesktop の利用方法によっては,変更通知サービスに 2 度登録され,同じ通知を 2 回受け取るようになります。
IsSupported
? / VirtualDesktop が IsSupported
であるか。https://github.com/Grabacr07/SylphyHorn/blob/092739797c40327c157acf3a1cd496cc4a53494a/source/SylphyHorn/Application.xaml.cs#L46
Default
. / Default の Instance で初期化される。VirtualDesktop/source/VirtualDesktop/VirtualDesktop.static.cs
Lines 93 to 116 in 9ae33b8
VirtualDesktop/source/VirtualDesktop/VirtualDesktopProvider.cs
Lines 68 to 69 in 6b6a5be
Visual Studio: 2022
Target Framework: net6.0-windows10.0.19041.0
Target runtime: win-x64
Deployment mode: Framework-dependant
Publish is successful but Exception when application is run at Production machines.
Called method: (or any other )
VirtualDesktop.FromHwnd(hWnd)
It returns following Exception
`Exception:Empty path name is not legal. (Parameter 'path')
StackTrace: at System.IO.Strategies.FileStreamHelpers.ValidateArguments(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, Int64 preallocationSize)
at Roslyn.Utilities.StandardFileSystem.OpenFile(String filePath, FileMode mode, FileAccess access, FileShare share)
at Roslyn.Utilities.CommonCompilerFileSystemExtensions.OpenFileWithNormalizedException(ICommonCompilerFileSystem fileSystem, String filePath, FileMode fileMode, FileAccess fileAccess, FileShare fileShare)
at WindowsDesktop.Interop.ComInterfaceAssemblyBuilder.<>c.b__14_2(Assembly x)
at System.Linq.Enumerable.WhereSelectEnumerableIterator2.MoveNext() at System.Collections.Generic.LargeArrayBuilder
1.AddRange(IEnumerable1 items) at System.Collections.Generic.EnumerableHelpers.ToArray[T](IEnumerable
1 source)
at System.Collections.Immutable.ImmutableArray.CreateRange[T](IEnumerable1 items) at Microsoft.CodeAnalysis.Compilation.ValidateReferences[T](IEnumerable
1 references)
at Microsoft.CodeAnalysis.CSharp.CSharpCompilation.WithReferences(IEnumerable1 references) at WindowsDesktop.Interop.ComInterfaceAssemblyBuilder.Compile(IEnumerable
1 sources)
at WindowsDesktop.Interop.ComInterfaceAssemblyBuilder.CreateAssembly()
at WindowsDesktop.Interop.ComInterfaceAssemblyBuilder.GetAssembly()
at WindowsDesktop.VirtualDesktop.InitializeCore()
at WindowsDesktop.VirtualDesktop.FromHwnd(IntPtr hWnd)
at MyProject.DB.DTOs.ActiveApplication.<>c__DisplayClass138_0.b__0() in D:/ProjectPath`
Any Help ?
Getting the error:
"Additional information: An invalid VARIANT was detected during a conversion from an unmanaged VARIANT to a managed object. Passing invalid VARIANTs to the CLR can cause unexpected exceptions, corruption or data loss"
Obviously I can turn that off so it doesn't appear, but I'm not sure the impact of ignoring it.
https://msdn.microsoft.com/en-us/library/7zw2e2w7(v=vs.110).aspx
Can be reproduced by going to Debug\Exceptions in the menu.
Expand Managed Debugging Assistants
Check Thrown under "InvalidVariant"
Then do something like this:
VirtualDesktop.CurrentChanged += (o, e) => Console.WriteLine("test");
And it usually pops up immediately, or right after to switch desktops.
while trying to this.MoveToDesktop(VirtualDesktop.Current);
When attempting to get instance of IVirtualDesktopManagerInternal
, I get null. (verified in the debugger)
I'm running Windows 10 Pro Insider Preview, Build 14372.rs1_release.160620-2342. This error didn't occur until I installed the Insider Preview, so hopefully it will resolve itself when the "Anniversary Update" is released in August.
It seems this library is no longer compatible with the desktop .NET Framework (only .NET Core). Is this intentional?
The issue seems to be that the System.Runtime.Loader
dependency is itself only compatible with .NET Core. I had tried adding the relevant NuGet package, but MSBuild would never deploy the assembly to my output directory. Some googling turned up a post where a Microsoft dev confirmed the incompatibility.
---------------------------
Failed to initialize.
---------------------------
Could not load file or assembly 'System.Runtime.Loader, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.
---------------------------
OK
---------------------------
Hi.
I've just updated my Windows, and library stop working throwning tihs message: "You must target Windows 10 in your app.manifest and run without debugging.".
Thanks in advance.
Getting a lot of the following logs in my use case:
shell\twinapi\virtualdesktops\lib\virtualdesktops.cpp(45)\twinapi.dll!00007FFB94775077: (caller: 00007FFB947754FD) ReturnHr(7701) tid(59e8) 8002802B Element not found.
shell\twinapi\virtualdesktops\lib\virtualdesktops.cpp(60)\twinapi.dll!00007FFB9477551C: (caller: 00007FFB05D46EE9) ReturnHr(7702) tid(59e8) 8002802B Element not found.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.