[AOT] move some LibraryImport define to common to avoid dup code (#40006)

<!-- Enter a brief description/summary of your PR here. What does it
fix/what does it change/how was it tested (even manually, if necessary)?
-->
## Summary of the Pull Request
To avoid dup code, try to move some LibraryImport define to common
folder.
This can make other modules/extensions easy to use.

<!-- Please review the items on the PR checklist before submitting-->
## PR Checklist

- [x] **Closes:** #xxx
- [x] **Communication:** I've discussed this with core contributors
already. If the work hasn't been agreed, this work might be rejected
- [x] **Tests:** Added/updated and all pass
- [ ] **Localization:** All end-user-facing strings can be localized
- [ ] **Dev docs:** Added/updated
- [ ] **New binaries:** Added on the required places
- [ ] [JSON for
signing](https://github.com/microsoft/PowerToys/blob/main/.pipelines/ESRPSigning_core.json)
for new binaries
- [ ] [WXS for
installer](https://github.com/microsoft/PowerToys/blob/main/installer/PowerToysSetup/Product.wxs)
for new binaries and localization folder
- [ ] [YML for CI
pipeline](https://github.com/microsoft/PowerToys/blob/main/.pipelines/ci/templates/build-powertoys-steps.yml)
for new test projects
- [ ] [YML for signed
pipeline](https://github.com/microsoft/PowerToys/blob/main/.pipelines/release.yml)
- [ ] **Documentation updated:** If checked, please file a pull request
on [our docs
repo](https://github.com/MicrosoftDocs/windows-uwp/tree/docs/hub/powertoys)
and link it here: #xxx

<!-- Provide a more detailed description of the PR, other things fixed,
or any additional comments/features here -->
## Detailed Description of the Pull Request / Additional comments

<!-- Describe how you validated the behavior. Add automated tests
wherever possible, but list manual validation steps taken as well -->
## Validation Steps Performed

---------

Co-authored-by: Yu Leng <yuleng@microsoft.com>
This commit is contained in:
Yu Leng
2025-06-19 13:45:44 +08:00
committed by GitHub
parent cc14fc3c89
commit 1020c5abae
30 changed files with 430 additions and 409 deletions

View File

@@ -723,6 +723,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WorkspacesEditorUITest", "s
EndProject EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "CalculatorEngineCommon", "src\common\CalculatorEngineCommon\CalculatorEngineCommon.vcxproj", "{2CF78CF7-8FEB-4BE1-9591-55FA25B48FC6}" Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "CalculatorEngineCommon", "src\common\CalculatorEngineCommon\CalculatorEngineCommon.vcxproj", "{2CF78CF7-8FEB-4BE1-9591-55FA25B48FC6}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ManagedCsWin32", "src\common\ManagedCsWin32\ManagedCsWin32.csproj", "{14AFD976-B4D2-49D0-9E6C-AA93CC061B8A}"
EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|ARM64 = Debug|ARM64 Debug|ARM64 = Debug|ARM64
@@ -2649,6 +2651,14 @@ Global
{2CF78CF7-8FEB-4BE1-9591-55FA25B48FC6}.Release|ARM64.Build.0 = Release|ARM64 {2CF78CF7-8FEB-4BE1-9591-55FA25B48FC6}.Release|ARM64.Build.0 = Release|ARM64
{2CF78CF7-8FEB-4BE1-9591-55FA25B48FC6}.Release|x64.ActiveCfg = Release|x64 {2CF78CF7-8FEB-4BE1-9591-55FA25B48FC6}.Release|x64.ActiveCfg = Release|x64
{2CF78CF7-8FEB-4BE1-9591-55FA25B48FC6}.Release|x64.Build.0 = Release|x64 {2CF78CF7-8FEB-4BE1-9591-55FA25B48FC6}.Release|x64.Build.0 = Release|x64
{14AFD976-B4D2-49D0-9E6C-AA93CC061B8A}.Debug|ARM64.ActiveCfg = Debug|ARM64
{14AFD976-B4D2-49D0-9E6C-AA93CC061B8A}.Debug|ARM64.Build.0 = Debug|ARM64
{14AFD976-B4D2-49D0-9E6C-AA93CC061B8A}.Debug|x64.ActiveCfg = Debug|x64
{14AFD976-B4D2-49D0-9E6C-AA93CC061B8A}.Debug|x64.Build.0 = Debug|x64
{14AFD976-B4D2-49D0-9E6C-AA93CC061B8A}.Release|ARM64.ActiveCfg = Release|ARM64
{14AFD976-B4D2-49D0-9E6C-AA93CC061B8A}.Release|ARM64.Build.0 = Release|ARM64
{14AFD976-B4D2-49D0-9E6C-AA93CC061B8A}.Release|x64.ActiveCfg = Release|x64
{14AFD976-B4D2-49D0-9E6C-AA93CC061B8A}.Release|x64.Build.0 = Release|x64
EndGlobalSection EndGlobalSection
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE
@@ -2926,6 +2936,7 @@ Global
{5F63C743-F6CE-4DBA-A200-2B3F8A14E8C2} = {3846508C-77EB-4034-A702-F8BB263C4F79} {5F63C743-F6CE-4DBA-A200-2B3F8A14E8C2} = {3846508C-77EB-4034-A702-F8BB263C4F79}
{2694E2FB-DCD5-4BFF-A418-B6C3C7CE3B8E} = {89E20BCE-EB9C-46C8-8B50-E01A82E6FDC3} {2694E2FB-DCD5-4BFF-A418-B6C3C7CE3B8E} = {89E20BCE-EB9C-46C8-8B50-E01A82E6FDC3}
{2CF78CF7-8FEB-4BE1-9591-55FA25B48FC6} = {1AFB6476-670D-4E80-A464-657E01DFF482} {2CF78CF7-8FEB-4BE1-9591-55FA25B48FC6} = {1AFB6476-670D-4E80-A464-657E01DFF482}
{14AFD976-B4D2-49D0-9E6C-AA93CC061B8A} = {1AFB6476-670D-4E80-A464-657E01DFF482}
EndGlobalSection EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {C3A2F9D1-7930-4EF4-A6FC-7EE0A99821D0} SolutionGuid = {C3A2F9D1-7930-4EF4-A6FC-7EE0A99821D0}

View File

@@ -0,0 +1,19 @@
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ManagedCsWin32;
public static partial class CLSID
{
public static readonly Guid SearchManager = new Guid("7D096C5F-AC08-4F1F-BEB7-5C22C517CE39");
public static readonly Guid CollatorDataSource = new Guid("9E175B8B-F52A-11D8-B9A5-505054503030");
public static readonly Guid ApplicationActivationManager = new Guid("45BA127D-10A8-46EA-8AB7-56EA9078943C");
public static readonly Guid VirtualDesktopManager = new("aa509086-5ca9-4c25-8f95-589d3c07b48a");
}

View File

@@ -0,0 +1,45 @@
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.Marshalling;
namespace ManagedCsWin32;
public static class ComHelper
{
private static StrategyBasedComWrappers cw = new StrategyBasedComWrappers();
public static T CreateComInstance<T>(ref Guid rclsid, CLSCTX dwClsContext)
{
var riid = typeof(T).GUID;
var hr = Ole32.CoCreateInstance(ref rclsid, IntPtr.Zero, dwClsContext, ref riid, out IntPtr comPtr);
if (hr != 0)
{
throw new ArgumentException($"Failed to create {typeof(T).Name} instance. HR: {hr}");
}
if (comPtr == IntPtr.Zero)
{
throw new ArgumentException($"Failed to create {typeof(T).Name} instance. CoCreateInstance return null ptr.");
}
try
{
var comObject = cw.GetOrCreateObjectForComInstance(comPtr, CreateObjectFlags.None);
if (comObject == null)
{
throw new ArgumentException($"Failed to create {typeof(T).Name} instance. Cast error.");
}
return (T)comObject;
}
finally
{
Marshal.Release(comPtr);
}
}
}

View File

@@ -0,0 +1,19 @@
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ManagedCsWin32;
public static partial class IID
{
public static readonly Guid ISearchManager = new Guid("AB310581-AC80-11D1-8DF3-00C04FB6EF69");
public static readonly Guid IPropertyStore = new Guid("886D8EEB-8CF2-4446-8D02-CDBA1DBDCF99");
public static readonly Guid IApplicationActivationManager = new Guid("2e941141-7f97-4756-ba1d-9decde894a3d");
public static readonly Guid IVirtualDesktopManager = new("a5cd92ff-29be-454c-8d04-d82879fb3f1b");
}

View File

@@ -0,0 +1,145 @@
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Runtime.InteropServices;
namespace ManagedCsWin32;
public static partial class Kernel32
{
[LibraryImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static partial bool DeviceIoControl(
IntPtr hDevice,
uint dwIoControlCode,
IntPtr inBuffer,
int nInBufferSize,
IntPtr outBuffer,
int nOutBufferSize,
out int pBytesReturned,
IntPtr lpOverlapped);
[LibraryImport("kernel32.dll", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)]
public static partial int CreateFile(
string lpFileName,
FileAccessType dwDesiredAccess,
FileShareType dwShareMode,
IntPtr lpSecurityAttributes,
CreationDisposition dwCreationDisposition,
FileAttributes dwFlagsAndAttributes,
IntPtr hTemplateFile);
}
[Flags]
public enum FileAccessType : uint
{
DELETE = 0x00010000,
READ_CONTROL = 0x00020000,
WRITE_DAC = 0x00040000,
WRITE_OWNER = 0x00080000,
SYNCHRONIZE = 0x00100000,
STANDARD_RIGHTS_REQUIRED = 0x000F0000,
STANDARD_RIGHTS_READ = READ_CONTROL,
STANDARD_RIGHTS_WRITE = READ_CONTROL,
STANDARD_RIGHTS_EXECUTE = READ_CONTROL,
STANDARD_RIGHTS_ALL = 0x001F0000,
SPECIFIC_RIGHTS_ALL = 0x0000FFFF,
ACCESS_SYSTEM_SECURITY = 0x01000000,
MAXIMUM_ALLOWED = 0x02000000,
GENERIC_READ = 0x80000000,
GENERIC_WRITE = 0x40000000,
GENERIC_EXECUTE = 0x20000000,
GENERIC_ALL = 0x10000000,
FILE_READ_DATA = 0x0001,
FILE_WRITE_DATA = 0x0002,
FILE_APPEND_DATA = 0x0004,
FILE_READ_EA = 0x0008,
FILE_WRITE_EA = 0x0010,
FILE_EXECUTE = 0x0020,
FILE_READ_ATTRIBUTES = 0x0080,
FILE_WRITE_ATTRIBUTES = 0x0100,
FILE_ALL_ACCESS =
STANDARD_RIGHTS_REQUIRED |
SYNCHRONIZE
| 0x1FF,
FILE_GENERIC_READ =
STANDARD_RIGHTS_READ |
FILE_READ_DATA |
FILE_READ_ATTRIBUTES |
FILE_READ_EA |
SYNCHRONIZE,
FILE_GENERIC_WRITE =
STANDARD_RIGHTS_WRITE |
FILE_WRITE_DATA |
FILE_WRITE_ATTRIBUTES |
FILE_WRITE_EA |
FILE_APPEND_DATA |
SYNCHRONIZE,
FILE_GENERIC_EXECUTE =
STANDARD_RIGHTS_EXECUTE |
FILE_READ_ATTRIBUTES |
FILE_EXECUTE |
SYNCHRONIZE,
}
[Flags]
public enum FileShareType : uint
{
None = 0x00000000,
Read = 0x00000001,
Write = 0x00000002,
Delete = 0x00000004,
}
public enum CreationDisposition : uint
{
New = 1,
CreateAlways = 2,
OpenExisting = 3,
OpenAlways = 4,
TruncateExisting = 5,
}
[Flags]
public enum FileAttributes : uint
{
Readonly = 0x00000001,
Hidden = 0x00000002,
System = 0x00000004,
Directory = 0x00000010,
Archive = 0x00000020,
Device = 0x00000040,
Normal = 0x00000080,
Temporary = 0x00000100,
SparseFile = 0x00000200,
ReparsePoint = 0x00000400,
Compressed = 0x00000800,
Offline = 0x00001000,
NotContentIndexed = 0x00002000,
Encrypted = 0x00004000,
Write_Through = 0x80000000,
Overlapped = 0x40000000,
NoBuffering = 0x20000000,
RandomAccess = 0x10000000,
SequentialScan = 0x08000000,
DeleteOnClose = 0x04000000,
BackupSemantics = 0x02000000,
PosixSemantics = 0x01000000,
OpenReparsePoint = 0x00200000,
OpenNoRecall = 0x00100000,
FirstPipeInstance = 0x00080000,
}

View File

@@ -0,0 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk">
<!-- Look at Directory.Build.props in root for common stuff as well -->
<Import Project="..\..\.\Common.Dotnet.CsWinRT.props" />
<PropertyGroup>
<Description>PowerToys ManagedCsWin32</Description>
<AssemblyName>PowerToys.ManagedCsWin32</AssemblyName>
</PropertyGroup>
</Project>

View File

@@ -0,0 +1,58 @@
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Runtime.InteropServices;
namespace ManagedCsWin32;
public static partial class Ole32
{
[LibraryImport("ole32.dll")]
public static partial int CoCreateInstance(
ref Guid rclsid,
IntPtr pUnkOuter,
CLSCTX dwClsContext,
ref Guid riid,
out IntPtr rReturnedComObject);
}
[Flags]
public enum CLSCTX : uint
{
InProcServer = 0x1,
InProcHandler = 0x2,
LocalServer = 0x4,
InProcServer16 = 0x8,
RemoteServer = 0x10,
InProcHandler16 = 0x20,
Reserved1 = 0x40,
Reserved2 = 0x80,
Reserved3 = 0x100,
Reserved4 = 0x200,
NoCodeDownload = 0x400,
Reserved5 = 0x800,
NoCustomMarshal = 0x1000,
EnableCodeDownload = 0x2000,
NoFailureLog = 0x4000,
DisableAAA = 0x8000,
EnableAAA = 0x10000,
FromDefaultContext = 0x20000,
ActivateX86Server = 0x40000,
#pragma warning disable CA1069 // Keep the original defines for compatibility
Activate32BitServer = 0x40000, // Same as ActivateX86Server
#pragma warning restore CA1069 // Keep the original defines for compatibility
Activate64BitServer = 0x80000,
EnableCloaking = 0x100000,
AppContainer = 0x400000,
ActivateAAAAsIU = 0x800000,
Reserved6 = 0x1000000,
ActivateARM32Server = 0x2000000,
AllowLowerTrustRegistration = 0x4000000,
PSDll = 0x80000000,
INPROC = InProcServer | InProcHandler,
SERVER = InProcServer | LocalServer | RemoteServer,
ALL = InProcHandler | SERVER,
}

View File

@@ -0,0 +1,36 @@
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Runtime.InteropServices;
namespace ManagedCsWin32;
public static partial class Shell32
{
[LibraryImport("SHELL32.dll", EntryPoint = "ShellExecuteExW", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static partial bool ShellExecuteEx(ref SHELLEXECUTEINFOW lpExecInfo);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct SHELLEXECUTEINFOW
{
public uint CbSize;
public uint FMask;
public IntPtr Hwnd;
public IntPtr LpVerb;
public IntPtr LpFile;
public IntPtr LpParameters;
public IntPtr LpDirectory;
public int Show;
public IntPtr HInstApp;
public IntPtr LpIDList;
public IntPtr LpClass;
public IntPtr HkeyClass;
public uint DwHotKey;
public IntPtr HIconOrMonitor;
public IntPtr Process;
}
}

View File

@@ -20,7 +20,7 @@
<PackageReference Include="WyHash" /> <PackageReference Include="WyHash" />
<ProjectReference Include="..\..\..\..\common\ManagedCommon\ManagedCommon.csproj" /> <ProjectReference Include="..\..\..\..\common\ManagedCommon\ManagedCommon.csproj" />
<ProjectReference Include="..\..\..\..\common\ManagedCsWin32\ManagedCsWin32.csproj" />
<ProjectReference Include="..\..\extensionsdk\Microsoft.CommandPalette.Extensions.Toolkit\Microsoft.CommandPalette.Extensions.Toolkit.csproj" /> <ProjectReference Include="..\..\extensionsdk\Microsoft.CommandPalette.Extensions.Toolkit\Microsoft.CommandPalette.Extensions.Toolkit.csproj" />
</ItemGroup> </ItemGroup>

View File

@@ -3,14 +3,12 @@
// See the LICENSE file in the project root for more information. // See the LICENSE file in the project root for more information.
using System; using System;
using System.ComponentModel;
using System.IO; using System.IO;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Text; using System.Text;
using ManagedCsWin32;
using Microsoft.Win32.SafeHandles; using Microsoft.Win32.SafeHandles;
using Windows.Storage.Streams;
namespace Microsoft.CmdPal.Ext.Apps.Programs; namespace Microsoft.CmdPal.Ext.Apps.Programs;
@@ -36,118 +34,6 @@ public static partial class ReparsePoint
private const int E_INVALID_PROTOCOL_FORMAT = unchecked((int)0x83760002); private const int E_INVALID_PROTOCOL_FORMAT = unchecked((int)0x83760002);
#pragma warning restore SA1310 // Field names should not contain underscore #pragma warning restore SA1310 // Field names should not contain underscore
[Flags]
internal enum FileAccessType : uint
{
DELETE = 0x00010000,
READ_CONTROL = 0x00020000,
WRITE_DAC = 0x00040000,
WRITE_OWNER = 0x00080000,
SYNCHRONIZE = 0x00100000,
STANDARD_RIGHTS_REQUIRED = 0x000F0000,
STANDARD_RIGHTS_READ = READ_CONTROL,
STANDARD_RIGHTS_WRITE = READ_CONTROL,
STANDARD_RIGHTS_EXECUTE = READ_CONTROL,
STANDARD_RIGHTS_ALL = 0x001F0000,
SPECIFIC_RIGHTS_ALL = 0x0000FFFF,
ACCESS_SYSTEM_SECURITY = 0x01000000,
MAXIMUM_ALLOWED = 0x02000000,
GENERIC_READ = 0x80000000,
GENERIC_WRITE = 0x40000000,
GENERIC_EXECUTE = 0x20000000,
GENERIC_ALL = 0x10000000,
FILE_READ_DATA = 0x0001,
FILE_WRITE_DATA = 0x0002,
FILE_APPEND_DATA = 0x0004,
FILE_READ_EA = 0x0008,
FILE_WRITE_EA = 0x0010,
FILE_EXECUTE = 0x0020,
FILE_READ_ATTRIBUTES = 0x0080,
FILE_WRITE_ATTRIBUTES = 0x0100,
FILE_ALL_ACCESS =
STANDARD_RIGHTS_REQUIRED |
SYNCHRONIZE
| 0x1FF,
FILE_GENERIC_READ =
STANDARD_RIGHTS_READ |
FILE_READ_DATA |
FILE_READ_ATTRIBUTES |
FILE_READ_EA |
SYNCHRONIZE,
FILE_GENERIC_WRITE =
STANDARD_RIGHTS_WRITE |
FILE_WRITE_DATA |
FILE_WRITE_ATTRIBUTES |
FILE_WRITE_EA |
FILE_APPEND_DATA |
SYNCHRONIZE,
FILE_GENERIC_EXECUTE =
STANDARD_RIGHTS_EXECUTE |
FILE_READ_ATTRIBUTES |
FILE_EXECUTE |
SYNCHRONIZE,
}
[Flags]
internal enum FileShareType : uint
{
None = 0x00000000,
Read = 0x00000001,
Write = 0x00000002,
Delete = 0x00000004,
}
internal enum CreationDisposition : uint
{
New = 1,
CreateAlways = 2,
OpenExisting = 3,
OpenAlways = 4,
TruncateExisting = 5,
}
[Flags]
internal enum FileAttributes : uint
{
Readonly = 0x00000001,
Hidden = 0x00000002,
System = 0x00000004,
Directory = 0x00000010,
Archive = 0x00000020,
Device = 0x00000040,
Normal = 0x00000080,
Temporary = 0x00000100,
SparseFile = 0x00000200,
ReparsePoint = 0x00000400,
Compressed = 0x00000800,
Offline = 0x00001000,
NotContentIndexed = 0x00002000,
Encrypted = 0x00004000,
Write_Through = 0x80000000,
Overlapped = 0x40000000,
NoBuffering = 0x20000000,
RandomAccess = 0x10000000,
SequentialScan = 0x08000000,
DeleteOnClose = 0x04000000,
BackupSemantics = 0x02000000,
PosixSemantics = 0x01000000,
OpenReparsePoint = 0x00200000,
OpenNoRecall = 0x00100000,
FirstPipeInstance = 0x00080000,
}
private enum AppExecutionAliasReparseTagBufferLayoutVersion : uint private enum AppExecutionAliasReparseTagBufferLayoutVersion : uint
{ {
Invalid = 0, Invalid = 0,
@@ -196,28 +82,6 @@ public static partial class ReparsePoint
public AppExecutionAliasReparseTagBufferLayoutVersion Version; public AppExecutionAliasReparseTagBufferLayoutVersion Version;
} }
[LibraryImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static partial bool DeviceIoControl(
IntPtr hDevice,
uint dwIoControlCode,
IntPtr inBuffer,
int nInBufferSize,
IntPtr outBuffer,
int nOutBufferSize,
out int pBytesReturned,
IntPtr lpOverlapped);
[LibraryImport("kernel32.dll", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)]
internal static partial int CreateFile(
string lpFileName,
FileAccessType dwDesiredAccess,
FileShareType dwShareMode,
IntPtr lpSecurityAttributes,
CreationDisposition dwCreationDisposition,
FileAttributes dwFlagsAndAttributes,
IntPtr hTemplateFile);
/// <summary> /// <summary>
/// Gets the target of the specified reparse point. /// Gets the target of the specified reparse point.
/// </summary> /// </summary>
@@ -231,13 +95,13 @@ public static partial class ReparsePoint
public static string? GetTarget(string reparsePoint) public static string? GetTarget(string reparsePoint)
{ {
using (SafeFileHandle reparsePointHandle = new SafeFileHandle( using (SafeFileHandle reparsePointHandle = new SafeFileHandle(
CreateFile( Kernel32.CreateFile(
reparsePoint, reparsePoint,
FileAccessType.FILE_READ_ATTRIBUTES | FileAccessType.FILE_READ_EA, FileAccessType.FILE_READ_ATTRIBUTES | FileAccessType.FILE_READ_EA,
FileShareType.Delete | FileShareType.Read | FileShareType.Write, FileShareType.Delete | FileShareType.Read | FileShareType.Write,
IntPtr.Zero, IntPtr.Zero,
CreationDisposition.OpenExisting, CreationDisposition.OpenExisting,
FileAttributes.OpenReparsePoint, ManagedCsWin32.FileAttributes.OpenReparsePoint,
IntPtr.Zero), IntPtr.Zero),
true)) true))
{ {
@@ -255,7 +119,7 @@ public static partial class ReparsePoint
for (var i = 0; i < 2; ++i) for (var i = 0; i < 2; ++i)
{ {
int bytesReturned; int bytesReturned;
var result = DeviceIoControl( var result = Kernel32.DeviceIoControl(
reparsePointHandle.DangerousGetHandle(), reparsePointHandle.DangerousGetHandle(),
FSCTL_GET_REPARSE_POINT, FSCTL_GET_REPARSE_POINT,
IntPtr.Zero, IntPtr.Zero,

View File

@@ -5,12 +5,8 @@
using System; using System;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using Microsoft.CmdPal.Ext.Indexer.Native; using ManagedCsWin32;
using Windows.Win32;
using Windows.Win32.Foundation;
using Windows.Win32.System.Com;
using WinRT; using WinRT;
using WinRT.Interop;
namespace Microsoft.CmdPal.Ext.Indexer.Data; namespace Microsoft.CmdPal.Ext.Indexer.Data;
@@ -29,7 +25,7 @@ internal static class ActionRuntimeFactory
Guid classId = Guid.Parse(ActionRuntimeClsidStr); Guid classId = Guid.Parse(ActionRuntimeClsidStr);
Guid iid = IActionRuntimeIID; Guid iid = IActionRuntimeIID;
var hresult = NativeMethods.CoCreateInstance(ref Unsafe.AsRef(in classId), IntPtr.Zero, NativeHelpers.CLSCTXLOCALSERVER, ref iid, out abiPtr); var hresult = Ole32.CoCreateInstance(ref Unsafe.AsRef(in classId), IntPtr.Zero, CLSCTX.LocalServer, ref iid, out abiPtr);
Marshal.ThrowExceptionForHR((int)hresult); Marshal.ThrowExceptionForHR((int)hresult);
return MarshalInterface<global::Windows.AI.Actions.ActionRuntime>.FromAbi(abiPtr); return MarshalInterface<global::Windows.AI.Actions.ActionRuntime>.FromAbi(abiPtr);

View File

@@ -3,18 +3,14 @@
// See the LICENSE file in the project root for more information. // See the LICENSE file in the project root for more information.
using System; using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using ManagedCommon; using ManagedCommon;
using ManagedCsWin32;
using Microsoft.CmdPal.Ext.Indexer.Data; using Microsoft.CmdPal.Ext.Indexer.Data;
using Microsoft.CmdPal.Ext.Indexer.Native; using Microsoft.CmdPal.Ext.Indexer.Indexer.Utils;
using Microsoft.CmdPal.Ext.Indexer.Properties; using Microsoft.CmdPal.Ext.Indexer.Properties;
using Microsoft.CommandPalette.Extensions.Toolkit; using Microsoft.CommandPalette.Extensions.Toolkit;
using Windows.Win32;
using Windows.Win32.Foundation;
using Windows.Win32.UI.Shell;
using Windows.Win32.UI.WindowsAndMessaging; using Windows.Win32.UI.WindowsAndMessaging;
using static Microsoft.CmdPal.Ext.Indexer.Native.NativeMethods;
namespace Microsoft.CmdPal.Ext.Indexer.Commands; namespace Microsoft.CmdPal.Ext.Indexer.Commands;
@@ -29,16 +25,16 @@ internal sealed partial class OpenPropertiesCommand : InvokableCommand
try try
{ {
var info = new SHELLEXECUTEINFOW var info = new Shell32.SHELLEXECUTEINFOW
{ {
cbSize = (uint)sizeof(SHELLEXECUTEINFOW), CbSize = (uint)sizeof(Shell32.SHELLEXECUTEINFOW),
lpVerb = propertiesPtr, LpVerb = propertiesPtr,
lpFile = filenamePtr, LpFile = filenamePtr,
nShow = (int)SHOW_WINDOW_CMD.SW_SHOW, Show = (int)SHOW_WINDOW_CMD.SW_SHOW,
fMask = NativeHelpers.SEEMASKINVOKEIDLIST, FMask = NativeHelpers.SEEMASKINVOKEIDLIST,
}; };
return ShellExecuteEx(ref info); return Shell32.ShellExecuteEx(ref info);
} }
finally finally
{ {

View File

@@ -2,18 +2,13 @@
// The Microsoft Corporation licenses this file to you under the MIT license. // The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information. // See the LICENSE file in the project root for more information.
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using ManagedCsWin32;
using Microsoft.CmdPal.Ext.Indexer.Data; using Microsoft.CmdPal.Ext.Indexer.Data;
using Microsoft.CmdPal.Ext.Indexer.Native; using Microsoft.CmdPal.Ext.Indexer.Indexer.Utils;
using Microsoft.CmdPal.Ext.Indexer.Properties; using Microsoft.CmdPal.Ext.Indexer.Properties;
using Microsoft.CommandPalette.Extensions.Toolkit; using Microsoft.CommandPalette.Extensions.Toolkit;
using Windows.Win32;
using Windows.Win32.Foundation;
using Windows.Win32.UI.Shell;
using Windows.Win32.UI.WindowsAndMessaging; using Windows.Win32.UI.WindowsAndMessaging;
using static Microsoft.CmdPal.Ext.Indexer.Native.NativeMethods;
namespace Microsoft.CmdPal.Ext.Indexer.Commands; namespace Microsoft.CmdPal.Ext.Indexer.Commands;
@@ -28,16 +23,16 @@ internal sealed partial class OpenWithCommand : InvokableCommand
try try
{ {
var info = new SHELLEXECUTEINFOW var info = new Shell32.SHELLEXECUTEINFOW
{ {
cbSize = (uint)sizeof(SHELLEXECUTEINFOW), CbSize = (uint)sizeof(Shell32.SHELLEXECUTEINFOW),
lpVerb = verbPtr, LpVerb = verbPtr,
lpFile = filenamePtr, LpFile = filenamePtr,
nShow = (int)SHOW_WINDOW_CMD.SW_SHOWNORMAL, Show = (int)SHOW_WINDOW_CMD.SW_SHOWNORMAL,
fMask = NativeHelpers.SEEMASKINVOKEIDLIST, FMask = NativeHelpers.SEEMASKINVOKEIDLIST,
}; };
return ShellExecuteEx(ref info); return Shell32.ShellExecuteEx(ref info);
} }
finally finally
{ {

View File

@@ -4,11 +4,9 @@
using System; using System;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.Marshalling;
using ManagedCommon; using ManagedCommon;
using ManagedCsWin32;
using Microsoft.CmdPal.Ext.Indexer.Indexer.SystemSearch; using Microsoft.CmdPal.Ext.Indexer.Indexer.SystemSearch;
using Microsoft.CmdPal.Ext.Indexer.Native;
namespace Microsoft.CmdPal.Ext.Indexer.Indexer; namespace Microsoft.CmdPal.Ext.Indexer.Indexer;
@@ -29,35 +27,19 @@ internal static class DataSourceManager
private static bool InitializeDataSource() private static bool InitializeDataSource()
{ {
var riid = typeof(IDBInitialize).GUID; var riid = typeof(IDBInitialize).GUID;
var hr = NativeMethods.CoCreateInstance(ref Unsafe.AsRef(in NativeHelpers.CsWin32GUID.CLSIDCollatorDataSource), IntPtr.Zero, NativeHelpers.CLSCTXINPROCALL, ref riid, out var dataSourceObjPtr);
if (hr != 0) try
{ {
Logger.LogError("CoCreateInstance failed: " + hr); _dataSource = ComHelper.CreateComInstance<IDBInitialize>(ref Unsafe.AsRef(in CLSID.CollatorDataSource), CLSCTX.InProcServer);
return false;
} }
catch (Exception e)
if (dataSourceObjPtr == IntPtr.Zero)
{ {
Logger.LogError("CoCreateInstance failed: dataSourceObjPtr is null"); Logger.LogError($"Failed to create datasource. ex: {e.Message}");
return false;
}
var comWrappers = new StrategyBasedComWrappers();
_dataSource = (IDBInitialize)comWrappers.GetOrCreateObjectForComInstance(dataSourceObjPtr, CreateObjectFlags.None);
if (_dataSource == null)
{
Logger.LogError("CoCreateInstance failed: dataSourceObj is null");
return false; return false;
} }
_dataSource.Initialize(); _dataSource.Initialize();
if (dataSourceObjPtr != IntPtr.Zero)
{
Marshal.Release(dataSourceObjPtr);
}
return true; return true;
} }
} }

View File

@@ -4,9 +4,7 @@
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using Microsoft.CmdPal.Ext.Indexer.Indexer.SystemSearch; using Microsoft.CmdPal.Ext.Indexer.Indexer.SystemSearch;
using Microsoft.CmdPal.Ext.Indexer.Native;
using Windows.Win32.Storage.IndexServer; using Windows.Win32.Storage.IndexServer;
using Windows.Win32.System.Com.StructuredStorage;
namespace Microsoft.CmdPal.Ext.Indexer.Indexer.OleDB; namespace Microsoft.CmdPal.Ext.Indexer.Indexer.OleDB;

View File

@@ -4,14 +4,15 @@
using System; using System;
using System.Collections.Concurrent; using System.Collections.Concurrent;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Threading; using System.Threading;
using ManagedCommon; using ManagedCommon;
using ManagedCsWin32;
using Microsoft.CmdPal.Ext.Indexer.Indexer.OleDB; using Microsoft.CmdPal.Ext.Indexer.Indexer.OleDB;
using Microsoft.CmdPal.Ext.Indexer.Indexer.SystemSearch; using Microsoft.CmdPal.Ext.Indexer.Indexer.SystemSearch;
using Microsoft.CmdPal.Ext.Indexer.Indexer.Utils; using Microsoft.CmdPal.Ext.Indexer.Indexer.Utils;
using Microsoft.CmdPal.Ext.Indexer.Native; using static Microsoft.CmdPal.Ext.Indexer.Indexer.Utils.NativeHelpers;
using static Microsoft.CmdPal.Ext.Indexer.Native.NativeHelpers;
namespace Microsoft.CmdPal.Ext.Indexer.Indexer; namespace Microsoft.CmdPal.Ext.Indexer.Indexer;
@@ -143,9 +144,7 @@ internal sealed partial class SearchQuery : IDisposable
{ {
try try
{ {
var riid = CsWin32GUID.PropertyStore; getRow.GetRowFromHROW(null, rowHandle, ref Unsafe.AsRef(in IID.IPropertyStore), out var propertyStore);
getRow.GetRowFromHROW(null, rowHandle, ref riid, out var propertyStore);
if (propertyStore == null) if (propertyStore == null)
{ {

View File

@@ -7,7 +7,6 @@ using System.Runtime.InteropServices;
using ManagedCommon; using ManagedCommon;
using Microsoft.CmdPal.Ext.Indexer.Indexer.SystemSearch; using Microsoft.CmdPal.Ext.Indexer.Indexer.SystemSearch;
using Microsoft.CmdPal.Ext.Indexer.Indexer.Utils; using Microsoft.CmdPal.Ext.Indexer.Indexer.Utils;
using Microsoft.CmdPal.Ext.Indexer.Native;
namespace Microsoft.CmdPal.Ext.Indexer.Indexer; namespace Microsoft.CmdPal.Ext.Indexer.Indexer;

View File

@@ -3,13 +3,8 @@
// See the LICENSE file in the project root for more information. // See the LICENSE file in the project root for more information.
using System; using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Runtime.InteropServices.Marshalling; using System.Runtime.InteropServices.Marshalling;
using System.Text;
using System.Threading.Tasks;
using Microsoft.CmdPal.Ext.Indexer.Native;
namespace Microsoft.CmdPal.Ext.Indexer.Indexer.SystemSearch; namespace Microsoft.CmdPal.Ext.Indexer.Indexer.SystemSearch;

View File

@@ -0,0 +1,24 @@
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using Microsoft.CmdPal.Ext.Indexer.Indexer.SystemSearch;
namespace Microsoft.CmdPal.Ext.Indexer.Indexer.Utils;
public sealed partial class NativeHelpers
{
public const uint SEEMASKINVOKEIDLIST = 12;
public struct PropertyKeys
{
public static readonly PropertyKey PKEYItemNameDisplay = new() { FmtID = new Guid("B725F130-47EF-101A-A5F1-02608C9EEBAC"), PID = 10 };
public static readonly PropertyKey PKEYItemUrl = new() { FmtID = new Guid("49691C90-7E17-101A-A91C-08002B2ECDA9"), PID = 9 };
public static readonly PropertyKey PKEYKindText = new() { FmtID = new Guid("F04BEF95-C585-4197-A2B7-DF46FDC9EE6D"), PID = 100 };
}
public static class OleDb
{
public static readonly Guid DbGuidDefault = new("C8B521FB-5CF3-11CE-ADE5-00AA0044773D");
}
}

View File

@@ -7,8 +7,9 @@ using System.Globalization;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Runtime.InteropServices.Marshalling; using System.Runtime.InteropServices.Marshalling;
using ManagedCommon;
using ManagedCsWin32;
using Microsoft.CmdPal.Ext.Indexer.Indexer.SystemSearch; using Microsoft.CmdPal.Ext.Indexer.Indexer.SystemSearch;
using Microsoft.CmdPal.Ext.Indexer.Native;
namespace Microsoft.CmdPal.Ext.Indexer.Indexer.Utils; namespace Microsoft.CmdPal.Ext.Indexer.Indexer.Utils;
@@ -29,21 +30,16 @@ internal sealed partial class QueryStringBuilder
{ {
if (queryHelper == null) if (queryHelper == null)
{ {
ComWrappers cw = new StrategyBasedComWrappers(); ISearchManager searchManager;
var searchManagerPtr = IntPtr.Zero;
var hr = NativeMethods.CoCreateInstance(ref Unsafe.AsRef(in NativeHelpers.CsWin32GUID.CLSIDSearchManager), IntPtr.Zero, NativeHelpers.CLSCTXINPROCALL, ref Unsafe.AsRef(in NativeHelpers.CsWin32GUID.IIDISearchManager), out searchManagerPtr); try
if (hr != 0)
{ {
throw new ArgumentException($"Failed to create SearchManager instance. HR: 0x{hr:X}"); searchManager = ComHelper.CreateComInstance<ISearchManager>(ref Unsafe.AsRef(in CLSID.SearchManager), CLSCTX.LocalServer);
} }
catch (Exception ex)
var searchManager = (ISearchManager)cw.GetOrCreateObjectForComInstance(
searchManagerPtr, CreateObjectFlags.None);
if (searchManager == null)
{ {
throw new ArgumentException("Failed to get ISearchManager interface"); Logger.LogError($"Failed to create searchManager. ex: {ex.Message}");
throw;
} }
ISearchCatalogManager catalogManager = searchManager.GetCatalog(SystemIndex); ISearchCatalogManager catalogManager = searchManager.GetCatalog(SystemIndex);
@@ -52,11 +48,6 @@ internal sealed partial class QueryStringBuilder
throw new ArgumentException($"Failed to get catalog manager for {SystemIndex}"); throw new ArgumentException($"Failed to get catalog manager for {SystemIndex}");
} }
if (searchManagerPtr != IntPtr.Zero)
{
Marshal.Release(searchManagerPtr);
}
queryHelper = catalogManager.GetQueryHelper(); queryHelper = catalogManager.GetQueryHelper();
if (queryHelper == null) if (queryHelper == null)
{ {

View File

@@ -15,8 +15,9 @@
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference> </PackageReference>
<ProjectReference Include="..\..\..\..\common\ManagedCommon\ManagedCommon.csproj" /> <ProjectReference Include="..\..\..\..\common\ManagedCommon\ManagedCommon.csproj" />
<ProjectReference Include="..\..\..\..\common\ManagedCsWin32\ManagedCsWin32.csproj" />
<ProjectReference Include="..\..\extensionsdk\Microsoft.CommandPalette.Extensions.Toolkit\Microsoft.CommandPalette.Extensions.Toolkit.csproj" /> <ProjectReference Include="..\..\extensionsdk\Microsoft.CommandPalette.Extensions.Toolkit\Microsoft.CommandPalette.Extensions.Toolkit.csproj" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

View File

@@ -1,35 +0,0 @@
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using Microsoft.CmdPal.Ext.Indexer.Indexer.SystemSearch;
namespace Microsoft.CmdPal.Ext.Indexer.Native;
public sealed partial class NativeHelpers
{
public const uint SEEMASKINVOKEIDLIST = 12;
public const uint CLSCTXINPROCALL = 0x17;
public const uint CLSCTXLOCALSERVER = 0x4;
public struct PropertyKeys
{
public static readonly PropertyKey PKEYItemNameDisplay = new() { FmtID = new System.Guid("B725F130-47EF-101A-A5F1-02608C9EEBAC"), PID = 10 };
public static readonly PropertyKey PKEYItemUrl = new() { FmtID = new System.Guid("49691C90-7E17-101A-A91C-08002B2ECDA9"), PID = 9 };
public static readonly PropertyKey PKEYKindText = new() { FmtID = new System.Guid("F04BEF95-C585-4197-A2B7-DF46FDC9EE6D"), PID = 100 };
}
public static class OleDb
{
public static readonly Guid DbGuidDefault = new("C8B521FB-5CF3-11CE-ADE5-00AA0044773D");
}
public static class CsWin32GUID
{
public static readonly Guid CLSIDSearchManager = new Guid("7D096C5F-AC08-4F1F-BEB7-5C22C517CE39");
public static readonly Guid IIDISearchManager = new Guid("AB310581-AC80-11D1-8DF3-00C04FB6EF69");
public static readonly Guid CLSIDCollatorDataSource = new Guid("9E175B8B-F52A-11D8-B9A5-505054503030");
public static readonly Guid PropertyStore = new Guid("886D8EEB-8CF2-4446-8D02-CDBA1DBDCF99");
}
}

View File

@@ -1,47 +0,0 @@
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.Marshalling;
using Windows.Win32.UI.Shell;
namespace Microsoft.CmdPal.Ext.Indexer.Native;
public sealed partial class NativeMethods
{
[LibraryImport("ole32.dll")]
[return: MarshalAs(UnmanagedType.U4)]
public static partial uint CoCreateInstance(
ref Guid rclsid,
IntPtr pUnkOuter,
uint dwClsContext,
ref Guid riid,
out IntPtr rReturnedComObject);
[LibraryImport("SHELL32.dll", EntryPoint = "ShellExecuteExW", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static partial bool ShellExecuteEx(ref SHELLEXECUTEINFOW lpExecInfo);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct SHELLEXECUTEINFOW
{
public uint cbSize;
public uint fMask;
public IntPtr hwnd;
public IntPtr lpVerb;
public IntPtr lpFile;
public IntPtr lpParameters;
public IntPtr lpDirectory;
public int nShow;
public IntPtr hInstApp;
public IntPtr lpIDList;
public IntPtr lpClass;
public IntPtr hkeyClass;
public uint dwHotKey;
public IntPtr hIconOrMonitor;
public IntPtr hProcess;
}
}

View File

@@ -98,15 +98,6 @@ public static partial class NativeMethods
[DllImport("kernel32.dll")] [DllImport("kernel32.dll")]
[return: MarshalAs(UnmanagedType.Bool)] [return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetFirmwareType(ref FirmwareType FirmwareType); public static extern bool GetFirmwareType(ref FirmwareType FirmwareType);
[LibraryImport("ole32.dll")]
[return: MarshalAs(UnmanagedType.U4)]
public static partial uint CoCreateInstance(
ref Guid rclsid,
IntPtr pUnkOuter,
uint dwClsContext,
ref Guid riid,
out IntPtr rReturnedComObject);
} }
[SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:Field names should not contain underscore", Justification = "These are the names used by win32.")] [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:Field names should not contain underscore", Justification = "These are the names used by win32.")]

View File

@@ -5,10 +5,11 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Runtime.InteropServices.Marshalling; using System.Runtime.InteropServices.Marshalling;
using System.Text; using System.Text;
using ManagedCsWin32;
using Microsoft.CmdPal.Ext.WindowWalker.Properties; using Microsoft.CmdPal.Ext.WindowWalker.Properties;
using Microsoft.CommandPalette.Extensions.Toolkit; using Microsoft.CommandPalette.Extensions.Toolkit;
using Microsoft.Win32; using Microsoft.Win32;
@@ -49,10 +50,6 @@ public class VirtualDesktopHelper
/// </summary> /// </summary>
private readonly List<Guid> _availableDesktops = []; private readonly List<Guid> _availableDesktops = [];
#pragma warning disable SA1306 // Field names should begin with lower-case letter
private readonly uint CLSCTXINPROCALL = 0x17;
#pragma warning restore SA1306 // Field names should begin with lower-case letter
/// <summary> /// <summary>
/// Id of the current visible Desktop. /// Id of the current visible Desktop.
/// </summary> /// </summary>
@@ -60,10 +57,6 @@ public class VirtualDesktopHelper
private static readonly CompositeFormat VirtualDesktopHelperDesktop = System.Text.CompositeFormat.Parse(Properties.Resources.VirtualDesktopHelper_Desktop); private static readonly CompositeFormat VirtualDesktopHelperDesktop = System.Text.CompositeFormat.Parse(Properties.Resources.VirtualDesktopHelper_Desktop);
private Guid iVirtualDesktopManagerCLSID = new("aa509086-5ca9-4c25-8f95-589d3c07b48a");
private Guid iVirtualDesktopManagerIID = new("a5cd92ff-29be-454c-8d04-d82879fb3f1b");
/// <summary> /// <summary>
/// Initializes a new instance of the <see cref="VirtualDesktopHelper"/> class. /// Initializes a new instance of the <see cref="VirtualDesktopHelper"/> class.
/// </summary> /// </summary>
@@ -71,30 +64,16 @@ public class VirtualDesktopHelper
public VirtualDesktopHelper(bool desktopListUpdate = false) public VirtualDesktopHelper(bool desktopListUpdate = false)
{ {
var cw = new StrategyBasedComWrappers(); var cw = new StrategyBasedComWrappers();
var virtualDesktopManagerPtr = IntPtr.Zero;
try try
{ {
var hr = NativeMethods.CoCreateInstance(ref this.iVirtualDesktopManagerCLSID, nint.Zero, CLSCTXINPROCALL, ref iVirtualDesktopManagerIID, out virtualDesktopManagerPtr); _virtualDesktopManager = ComHelper.CreateComInstance<IVirtualDesktopManager>(ref Unsafe.AsRef(in CLSID.VirtualDesktopManager), CLSCTX.InProcServer);
if (hr != 0)
{
throw new ArgumentException($"Failed to create IVirtualDesktopManager instance. HR: 0x{hr:X}");
}
_virtualDesktopManager = (IVirtualDesktopManager)cw.GetOrCreateObjectForComInstance(virtualDesktopManagerPtr, CreateObjectFlags.None);
} }
catch (COMException ex) catch (COMException ex)
{ {
ExtensionHost.LogMessage(new LogMessage() { Message = $"Initialization of <VirtualDesktopHelper> failed: An exception was thrown when creating the instance of COM interface <IVirtualDesktopManager>. {ex} " }); ExtensionHost.LogMessage(new LogMessage() { Message = $"Initialization of <VirtualDesktopHelper> failed: An exception was thrown when creating the instance of COM interface <IVirtualDesktopManager>. {ex} " });
return; return;
} }
finally
{
if (virtualDesktopManagerPtr != IntPtr.Zero)
{
Marshal.Release(virtualDesktopManagerPtr);
}
}
_isWindowsEleven = OSVersionHelper.IsWindows11(); _isWindowsEleven = OSVersionHelper.IsWindows11();
_desktopListAutoUpdate = desktopListUpdate; _desktopListAutoUpdate = desktopListUpdate;

View File

@@ -15,6 +15,7 @@
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\..\..\..\common\ManagedCommon\ManagedCommon.csproj" /> <ProjectReference Include="..\..\..\..\common\ManagedCommon\ManagedCommon.csproj" />
<ProjectReference Include="..\..\extensionsdk\Microsoft.CommandPalette.Extensions.Toolkit\Microsoft.CommandPalette.Extensions.Toolkit.csproj" /> <ProjectReference Include="..\..\extensionsdk\Microsoft.CommandPalette.Extensions.Toolkit\Microsoft.CommandPalette.Extensions.Toolkit.csproj" />
<ProjectReference Include="..\..\..\..\common\ManagedCsWin32\ManagedCsWin32.csproj" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Update="Properties\Resources.Designer.cs"> <Compile Update="Properties\Resources.Designer.cs">

View File

@@ -7,6 +7,7 @@ using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Runtime.InteropServices.Marshalling; using System.Runtime.InteropServices.Marshalling;
using ManagedCommon; using ManagedCommon;
using ManagedCsWin32;
using Microsoft.CmdPal.Ext.WindowsTerminal.Helpers; using Microsoft.CmdPal.Ext.WindowsTerminal.Helpers;
using Microsoft.CmdPal.Ext.WindowsTerminal.Properties; using Microsoft.CmdPal.Ext.WindowsTerminal.Properties;
using Microsoft.CommandPalette.Extensions.Toolkit; using Microsoft.CommandPalette.Extensions.Toolkit;
@@ -63,22 +64,16 @@ internal sealed partial class LaunchProfileAsAdminCommand : InvokableCommand
private void Launch(string id, string profile) private void Launch(string id, string profile)
{ {
ComWrappers cw = new StrategyBasedComWrappers(); IApplicationActivationManager appManager;
var appManagerPtr = IntPtr.Zero;
var hr = NativeHelpers.CoCreateInstance(ref Unsafe.AsRef(in NativeHelpers.ApplicationActivationManagerCLSID), IntPtr.Zero, NativeHelpers.CLSCTXINPROCALL, ref Unsafe.AsRef(in NativeHelpers.ApplicationActivationManagerIID), out appManagerPtr); try
if (hr != 0)
{ {
throw new ArgumentException($"Failed to create IApplicationActivationManager instance. HR: 0x{hr:X}"); appManager = ComHelper.CreateComInstance<IApplicationActivationManager>(ref Unsafe.AsRef(in CLSID.ApplicationActivationManager), CLSCTX.InProcServer);
} }
catch (Exception e)
var appManager = (IApplicationActivationManager)cw.GetOrCreateObjectForComInstance(
appManagerPtr, CreateObjectFlags.None);
if (appManager == null)
{ {
throw new ArgumentException("Failed to get IApplicationActivationManager interface"); Logger.LogError($"Failed to create IApplicationActivationManager instance. ex: {e.Message}");
throw;
} }
const ActivateOptions noFlags = ActivateOptions.None; const ActivateOptions noFlags = ActivateOptions.None;
@@ -97,13 +92,6 @@ internal sealed partial class LaunchProfileAsAdminCommand : InvokableCommand
// _context.API.ShowMsg(name, message, string.Empty); // _context.API.ShowMsg(name, message, string.Empty);
Logger.LogError($"Failed to open Windows Terminal: {ex.Message}"); Logger.LogError($"Failed to open Windows Terminal: {ex.Message}");
} }
finally
{
if (appManagerPtr != IntPtr.Zero)
{
Marshal.Release(appManagerPtr);
}
}
} }
#pragma warning restore IDE0059, CS0168 #pragma warning restore IDE0059, CS0168

View File

@@ -7,6 +7,7 @@ using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Runtime.InteropServices.Marshalling; using System.Runtime.InteropServices.Marshalling;
using ManagedCommon; using ManagedCommon;
using ManagedCsWin32;
using Microsoft.CmdPal.Ext.WindowsTerminal.Helpers; using Microsoft.CmdPal.Ext.WindowsTerminal.Helpers;
using Microsoft.CmdPal.Ext.WindowsTerminal.Properties; using Microsoft.CmdPal.Ext.WindowsTerminal.Properties;
using Microsoft.CommandPalette.Extensions.Toolkit; using Microsoft.CommandPalette.Extensions.Toolkit;
@@ -33,21 +34,16 @@ internal sealed partial class LaunchProfileCommand : InvokableCommand
private void Launch(string id, string profile) private void Launch(string id, string profile)
{ {
ComWrappers cw = new StrategyBasedComWrappers(); IApplicationActivationManager appManager;
var appManagerPtr = IntPtr.Zero;
var hr = NativeHelpers.CoCreateInstance(ref Unsafe.AsRef(in NativeHelpers.ApplicationActivationManagerCLSID), IntPtr.Zero, NativeHelpers.CLSCTXINPROCALL, ref Unsafe.AsRef(in NativeHelpers.ApplicationActivationManagerIID), out appManagerPtr); try
if (hr != 0)
{ {
throw new ArgumentException($"Failed to create IApplicationActivationManager instance. HR: 0x{hr:X}"); appManager = ComHelper.CreateComInstance<IApplicationActivationManager>(ref Unsafe.AsRef(in CLSID.ApplicationActivationManager), CLSCTX.InProcServer);
} }
catch (Exception e)
var appManager = (IApplicationActivationManager)cw.GetOrCreateObjectForComInstance(
appManagerPtr, CreateObjectFlags.None);
if (appManager == null)
{ {
throw new ArgumentException("Failed to get IApplicationActivationManager interface"); Logger.LogError($"Failed to create IApplicationActivationManager instance. ex: {e.Message}");
throw;
} }
const ActivateOptions noFlags = ActivateOptions.None; const ActivateOptions noFlags = ActivateOptions.None;
@@ -66,13 +62,6 @@ internal sealed partial class LaunchProfileCommand : InvokableCommand
// _context.API.ShowMsg(name, message, string.Empty); // _context.API.ShowMsg(name, message, string.Empty);
Logger.LogError($"Failed to open Windows Terminal: {ex.Message}"); Logger.LogError($"Failed to open Windows Terminal: {ex.Message}");
} }
finally
{
if (appManagerPtr != IntPtr.Zero)
{
Marshal.Release(appManagerPtr);
}
}
} }
#pragma warning restore IDE0059, CS0168 #pragma warning restore IDE0059, CS0168

View File

@@ -1,28 +0,0 @@
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace Microsoft.CmdPal.Ext.WindowsTerminal.Helpers;
public sealed partial class NativeHelpers
{
public const uint CLSCTXINPROCALL = 0x17;
[LibraryImport("ole32.dll")]
public static partial uint CoCreateInstance(
ref Guid rclsid,
IntPtr pUnkOuter,
uint dwClsContext,
ref Guid riid,
out IntPtr rReturnedComObject);
public static readonly Guid ApplicationActivationManagerCLSID = new Guid("45BA127D-10A8-46EA-8AB7-56EA9078943C");
public static readonly Guid ApplicationActivationManagerIID = new Guid("2e941141-7f97-4756-ba1d-9decde894a3d");
}

View File

@@ -17,6 +17,7 @@
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\..\..\..\common\ManagedCommon\ManagedCommon.csproj" /> <ProjectReference Include="..\..\..\..\common\ManagedCommon\ManagedCommon.csproj" />
<ProjectReference Include="..\..\extensionsdk\Microsoft.CommandPalette.Extensions.Toolkit\Microsoft.CommandPalette.Extensions.Toolkit.csproj" /> <ProjectReference Include="..\..\extensionsdk\Microsoft.CommandPalette.Extensions.Toolkit\Microsoft.CommandPalette.Extensions.Toolkit.csproj" />
<ProjectReference Include="..\..\..\..\common\ManagedCsWin32\ManagedCsWin32.csproj" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Update="Properties\Resources.Designer.cs"> <Compile Update="Properties\Resources.Designer.cs">