【UWP】让 UWP 自己和自己通信

打印 上一主题 下一主题

主题 1737|帖子 1737|积分 5213

众所周知,UWP 一般是运行在沙盒内里的,当我们需要访问沙盒外资源的时间,就需要通过沙盒外的署理服务器来获取。一般情况下我们都是利用 WinRT API 通过 Runtime Broker 来和沙盒外互通,遇到要自定义的情况则是手动开一个 Win32 服务器来互通,但是有没有可能我们可以直接拿 UWP 本体当服务器呢?
UWP 本体现实上就是一个普通的 Win32 EXE 程序,只是想要以 UWP 状态运行只能通过系统托管,但是如果我们不需要它以 UWP 状态执行的时间完全可以直接双击打开它,这时间它就是一个很普通的散装 Win32 程序了。
利用这个特性,我们可以制作一种假装双击打开的方法,只需要在发现是 Win32 状态下启动就去用 API 唤起 UWP 形态的自己就行了。
  1. private static unsafe bool IsPackagedApp
  2. {
  3.     get
  4.     {
  5.         uint length = 0;
  6.         PWSTR str = new();
  7.         _ = PInvoke.GetCurrentPackageFullName(ref length, str);
  8.         char* ptr = stackalloc char[(int)length];
  9.         str = new(ptr);
  10.         WIN32_ERROR result = PInvoke.GetCurrentPackageFullName(ref length, str);
  11.         return result != WIN32_ERROR.APPMODEL_ERROR_NO_PACKAGE;
  12.     }
  13. }
  14. private static void Main()
  15. {
  16.     if (IsPackagedApp)
  17.     {
  18.         Application.Start(static p =>
  19.         {
  20.             DispatcherQueueSynchronizationContext context = new(DispatcherQueue.GetForCurrentThread());
  21.             SynchronizationContext.SetSynchronizationContext(context);
  22.             _ = new App();
  23.         });
  24.     }
  25.     else
  26.     {
  27.         StartCoreApplicationAsync().Wait();
  28.     }
  29. }
  30. private static async Task StartCoreApplicationAsync()
  31. {
  32.     PackageManager manager = new();
  33.     string basePath = AppDomain.CurrentDomain.BaseDirectory;
  34.     XmlDocument manifest = await XmlDocument.LoadFromFileAsync(await StorageFile.GetFileFromPathAsync(Path.Combine(basePath, "AppxManifest.xml")));
  35.     IXmlNode identity = manifest.GetElementsByTagName("Identity")?[0];
  36.     string name = identity.Attributes.FirstOrDefault(x => x.NodeName == "Name")?.InnerText;
  37.     IXmlNode application = manifest.GetElementsByTagName("Application")?[0];
  38.     string id = application.Attributes.FirstOrDefault(x => x.NodeName == "Id")?.InnerText;
  39.     IEnumerable<Package> packages = manager.FindPackagesForUser(string.Empty).Where(x => x.Id.FamilyName.StartsWith(name));
  40.     if (packages.FirstOrDefault() is Package package)
  41.     {
  42.         IReadOnlyList<AppListEntry> entries = await package.GetAppListEntriesAsync();
  43.         if (entries?[0] is AppListEntry entry)
  44.         {
  45.             _ = await entry.LaunchAsync();
  46.         }
  47.     }
  48. }
复制代码
既然我们可以让自己唤起自己,那么自己和自己通信也不是什么难事了,我们只需要在 UWP 形态下唤起一个 Win32 的自己,就可以自己利用自己滥权(bushi)了。
既然知道了原理可行,那么我们就来尝试把它造出来,众所周知,通信的方法有很多,比如 UWP 扩展通信、TCP 通信、管道通信甚至是写文件通信,但是这些用起来都太复杂了,既然我们已经用了 WinRT,那么我们直接用 WinRT 通信就是了。
不过真正的 OOP/WinRT 通信的例子并不多,我到目前为止也没有乐成实现,所以就先用 COM 通信充数了。如今微软到处都是 OOP/COM 通信,比如小组件和 Dev Home,自从微软疯狂用 OOP/COM 造插件之后这方面的示例已经非常多了,这里就展示一下怎样用 C# 实现基于 OOP/COM 的 WinRT 通信。
既然是通信,肯定要有服务器和客户端,这里这两个都是自己,所以我们就只需要创建一个 UWP 项目就行了。由于 C#/WinRT 并不能实现 WinRT 类与非 WinRT 类混编,所以我们还需要创建一个 C++/WinRT 项目来天生 winmd 清单,这个 C++ 项目可以精简一下,只需要能编译 IDL 文件就行了,固然不修改也可以,只是看起来不太清爽罢了。
由于 C++/WinRT 项目只负责天生清单,如果直接引用该项目会报找不到 dll 实现,所以我们需要把 winmd 文件单独拿出来,在 vcxprj 中添加任务:
  1. <Target Name="OutputWinMD" BeforeTargets="BuildCompile">
  2.   <PropertyGroup>
  3.     <PlatformName Condition="'$(Platform)' == 'Win32'">x86</PlatformName>
  4.     <PlatformName Condition="'$(Platform)' == 'ARM64EC'">ARM64</PlatformName>
  5.     <PlatformName Condition="'$(PlatformName)' == ''">$(Platform)</PlatformName>
  6.   </PropertyGroup>
  7.   <Copy SourceFiles="$(OutDir)\$(ProjectName).winmd" DestinationFolder="..\WinMD\$(PlatformName)\$(Configuration)" />
  8.   <Message Text="Copied output metadata file to '..\WinMD\$(PlatformName)\$(Configuration)\'." />
  9. </Target>
复制代码
如许当项目编译完成后就会把 winmd 复制到..\WinMD\$(PlatformName)\$(Configuration)\内里,这个文件夹是什么可以根据情况修改,注意只复制 winmd 文件。
接着我们在 UWP 项目引用 winmd 文件 (SelfCOMServer.Metadata替换成现实值):
  1. <ItemGroup>
  2.   <CsWinRTInputs Include="..\WinMD\$(Platform)\$(Configuration)\SelfCOMServer.Metadata.winmd" />
  3. </ItemGroup>
  4. <ItemGroup>
  5.   <None Include="..\WinMD\$(Platform)\$(Configuration)\SelfCOMServer.Metadata.winmd" Visible="False">
  6.     <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
  7.   </None>
  8. </ItemGroup>
复制代码
接下来我们就可以开始写 COM 类了,首先我们要实现一个负责服务器管理的类,这个类用来管理服务器的声明周期和远程类的获取方法。
其中我们需要先实现一种让服务器可以在客户端关闭后自动关闭的方法,让客户端通知是很不公道的,因为客户端可能会突然暴毙,如许就会导致服务器永远也不会释放了,所以我们必须让服务器去感知客户端不再需要服务器了。在 C++,我们可以通过观察引用计数的方法来知道远程类是否被客户端释放了,但是在 C#,远程类被客户端释放后并不会真的释放,我临时不清楚其中的原因,体现出来就是解构方法并不会被执行,所以我们就无法通过类释放来关闭服务器了。于是我们还有一种方法,当通信断开后,我们执行远程方法就会报错,如许我们就知道通信已经断开了,于是我们可以让客户端给服务器发送一个保活委托,服务器每隔一段时间就去执行一次,如许通信断开后再执行委托就会直接报错了。固然我们还可以让这个保活委托变成一个永远也不会结束的异步,让 WinRT 自己去等待,如许服务器在通信断开的一瞬间知道通信结束了,不过由于我们并不需要瞬间就反应,有时间我们还需要考虑应用被关闭后马上就又打开的情况,所以我照旧选择自己开个隔断比较长的定时器自己喂狗了。
实现很简单,开个定时器喂狗就行了:
  1. /// <summary>
  2. /// Represents a monitor that checks if a remote object is alive.
  3. /// </summary>
  4. public sealed partial class RemoteMonitor : IDisposable
  5. {
  6.     private bool disposed;
  7.     private readonly Timer _timer;
  8.     private readonly Action _dispose;
  9.     /// <summary>
  10.     /// Initializes a new instance of the <see cref="RemoteMonitor"/> class.
  11.     /// </summary>
  12.     /// <param name="handler">The handler to check if the remote object is alive.</param>
  13.     /// <param name="dispose">The action to dispose the remote object.</param>
  14.     /// <param name="period">The period to check if the remote object is alive.</param>
  15.     public RemoteMonitor(IsAliveHandler handler, Action dispose, TimeSpan period)
  16.     {
  17.         _dispose = dispose;
  18.         _timer = new(_ =>
  19.         {
  20.             bool isAlive = false;
  21.             try
  22.             {
  23.                 isAlive = handler.Invoke();
  24.             }
  25.             catch
  26.             {
  27.                 isAlive = false;
  28.             }
  29.             finally
  30.             {
  31.                 if (!isAlive)
  32.                 {
  33.                     Dispose();
  34.                 }
  35.             }
  36.         }, null, TimeSpan.Zero, period);
  37.     }
  38.     /// <summary>
  39.     /// Finalizes the instance of the <see cref="RemoteMonitor"/> class.
  40.     /// </summary>
  41.     ~RemoteMonitor() => Dispose();
  42.     /// <inheritdoc/>
  43.     public void Dispose()
  44.     {
  45.         if (!disposed)
  46.         {
  47.             disposed = true;
  48.             _timer.Dispose();
  49.             _dispose?.Invoke();
  50.             GC.SuppressFinalize(this);
  51.         }
  52.     }
  53. }
复制代码
同时在 IDL 定义IsAliveHandler委托:
  1. delegate Boolean IsAliveHandler();
复制代码
接下来我们就可以写服务器管理类了,我们只需要让它能正确释放服务器就行了,分别写 IDL 定义和 C# 实现:
  1. interface ISetMonitor
  2. {
  3.     void SetMonitor(IsAliveHandler handler, Windows.Foundation.TimeSpan period);
  4. }
  5. interface IRemoteThing requires ISetMonitor, Windows.Foundation.IClosable, Windows.Foundation.IStringable
  6. {
  7.     // 其他远程操作
  8. }
复制代码
  1. /// <summary>
  2. /// The manage class for remote object.
  3. /// </summary>
  4. public sealed partial class RemoteThing : IRemoteThing
  5. {
  6.     private bool disposed;
  7.     private RemoteMonitor _monitor;
  8.     /// <summary>
  9.     /// Initializes a new instance of the <see cref="RemoteThing"/> class.
  10.     /// </summary>
  11.     public RemoteThing() => Program.RefCount++;
  12.     /// <summary>
  13.     /// Finalizes the instance of the <see cref="RemoteThing"/> class.
  14.     /// </summary>
  15.     ~RemoteThing() => Dispose();
  16.     /// <summary>
  17.     /// Sets the monitor to check if the remote object is alive.
  18.     /// </summary>
  19.     /// <param name="handler">The handler to check if the remote object is alive.</param>
  20.     /// <param name="period">The period to check if the remote object is alive.</param>
  21.     public void SetMonitor(IsAliveHandler handler, TimeSpan period) => _monitor = new RemoteMonitor(handler, Dispose, period);
  22.     #region 其他远程操作
  23.     #endregion
  24.     /// <inheritdoc/>
  25.     public void Dispose()
  26.     {
  27.         if (!disposed)
  28.         {
  29.             disposed = true;
  30.             _monitor?.Dispose();
  31.             GC.SuppressFinalize(this);
  32.             if (--Program.RefCount == 0)
  33.             {
  34.                 _ = Program.CheckComRefAsync();
  35.             }
  36.         }
  37.     }
  38.     /// <summary>
  39.     /// 随便写点什么作为测试。
  40.     /// </summary>
  41.     public override string ToString() =>
  42.         new StringBuilder()
  43.             .AppendLine("Information")
  44.             .AppendLine($"Framework: {RuntimeInformation.FrameworkDescription}")
  45.             .AppendLine($"OSPlatform: {Environment.OSVersion}")
  46.             .Append($"OSArchitecture: {RuntimeInformation.OSArchitecture}")
  47.             .ToString();
  48. }
复制代码
有了服务器管理类,我们就可以把它注册到 COM 服务器了。想要注册 COM 类,我们需要一个  Factory 工厂类来让 COM 服务器可以在通信时初始化 COM 类。首先我们需要导入 COM 相关 API,定义IClassFactory接口,其中Factory.CLSID_IRemoteThing为远程类的CLSID。
  1. public static partial class Factory
  2. {
  3.     public static readonly Guid CLSID_IRemoteThing = new("01153FC5-2F29-4F60-93AD-EFFB97CC9E20");
  4.     public static readonly Guid CLSID_IUnknown = new("00000000-0000-0000-C000-000000000046");
  5.     [LibraryImport("api-ms-win-core-com-l1-1-0.dll")]
  6.     internal static partial int CoRegisterClassObject(in Guid rclsid, IClassFactory pUnk, uint dwClsContext, int flags, out uint lpdwRegister);
  7.     [LibraryImport("api-ms-win-core-com-l1-1-0.dll")]
  8.     internal static partial int CoRevokeClassObject(uint dwRegister);
  9. }
  10. // https://docs.microsoft.com/windows/win32/api/unknwn/nn-unknwn-iclassfactory
  11. [GeneratedComInterface]
  12. [Guid("00000001-0000-0000-C000-000000000046")]
  13. public partial interface IClassFactory
  14. {
  15.     void CreateInstance(nint pUnkOuter, in Guid riid, out nint ppvObject);
  16.     void LockServer([MarshalAs(UnmanagedType.Bool)] bool fLock);
  17. }
复制代码
接下来我们可以制作一个抽象的工厂类,然后就可以直接继承这个工厂类来实现对应类的工厂类,不过由于 COM 源天生临时不支持泛型,所以这个抽象的工厂类不能加GeneratedComClass。
  1. public abstract partial class Factory<T, TInterface> : IActivationFactory, IClassFactory where T : TInterface, new()
  2. {
  3.     private const int E_NOINTERFACE = unchecked((int)0x80004002);
  4.     private const int CLASS_E_NOAGGREGATION = unchecked((int)0x80040110);
  5.     private readonly Guid _iid = typeof(TInterface).GUID;
  6.     public nint ActivateInstance() => MarshalInspectable<TInterface>.FromManaged(new T());
  7.     public void CreateInstance(nint pUnkOuter, in Guid riid, out nint ppvObject)
  8.     {
  9.         ppvObject = 0;
  10.         if (pUnkOuter != 0)
  11.         {
  12.             Marshal.ThrowExceptionForHR(CLASS_E_NOAGGREGATION);
  13.         }
  14.         if (riid == _iid || riid == Factory.CLSID_IUnknown)
  15.         {
  16.             // Create the instance of the .NET object
  17.             ppvObject = MarshalInspectable<TInterface>.FromManaged(new T());
  18.         }
  19.         else
  20.         {
  21.             // The object that ppvObject points to does not support the
  22.             // interface identified by riid.
  23.             Marshal.ThrowExceptionForHR(E_NOINTERFACE);
  24.         }
  25.     }
  26.     public void LockServer([MarshalAs(UnmanagedType.Bool)] bool fLock)
  27.     {
  28.     }
  29.     public abstract void RegisterClassObject();
  30.     public abstract void RevokeClassObject();
  31. }
复制代码
然后我们继承这个抽象的工厂类来实现我们需要的工厂类:
  1. [GeneratedComClass]
  2. public partial class RemoteThingFactory : Factory<RemoteThing, IRemoteThing>
  3. {
  4.     private uint cookie;
  5.     public override void RegisterClassObject()
  6.     {
  7.         int hresult = Factory.CoRegisterClassObject(
  8.             Factory.CLSID_IRemoteThing,
  9.             this,
  10.             (uint)CLSCTX.CLSCTX_LOCAL_SERVER,
  11.             (int)REGCLS.REGCLS_MULTIPLEUSE,
  12.             out cookie);
  13.         if (hresult < 0)
  14.         {
  15.             Marshal.ThrowExceptionForHR(hresult);
  16.         }
  17.     }
  18.     public override void RevokeClassObject()
  19.     {
  20.         int hresult = Factory.CoRevokeClassObject(cookie);
  21.         if (hresult < 0)
  22.         {
  23.             Marshal.ThrowExceptionForHR(hresult);
  24.         }
  25.     }
  26. }
复制代码
然后我们就可以在程序入口点注册这个 COM 类了:
  1. public static class Program
  2. {
  3.     private static ManualResetEventSlim comServerExitEvent;
  4.     public static int RefCount { get; set; }
  5.     private static void Main(string[] args)
  6.     {
  7.         if (args is ["-RegisterProcessAsComServer", ..])
  8.         {
  9.             comServerExitEvent = new ManualResetEventSlim(false);
  10.             comServerExitEvent.Reset();
  11.             RemoteThingFactory factory = new();
  12.             factory.RegisterClassObject();
  13.             _ = CheckComRefAsync();
  14.             comServerExitEvent.Wait();
  15.             factory.RevokeClassObject();
  16.         }
  17.         else
  18.         {
  19.             Application.Start(static p =>
  20.             {
  21.                 DispatcherQueueSynchronizationContext context = new(DispatcherQueue.GetForCurrentThread());
  22.                 SynchronizationContext.SetSynchronizationContext(context);
  23.                 _ = new App();
  24.             });
  25.         }
  26.     }
  27.     public static async Task CheckComRefAsync()
  28.     {
  29.         await Task.Delay(100);
  30.         if (RefCount == 0)
  31.         {
  32.             comServerExitEvent?.Set();
  33.         }
  34.     }
  35. }
复制代码
最后我们需要在清单声明 COM 服务器,其中SelfCOMServer.exe为服务器所在的可执行文件,Class ID 填远程类的CLSID。
  1. <Applications>
  2.   <Application>
  3.     ...
  4.     <Extensions>
  5.       <com:Extension Category="windows.comServer">
  6.         <com:ComServer>
  7.           <com:ExeServer
  8.             Executable="SelfCOMServer.exe"
  9.             Arguments="-RegisterProcessAsComServer"
  10.             DisplayName="COM Server"
  11.             LaunchAndActivationPermission="O:SYG:SYD:(A;;11;;;WD)(A;;11;;;RC)(A;;11;;;AC)(A;;11;;;AN)S:P(ML;;NX;;;S-1-16-0)">
  12.             <com:Class Id="01153FC5-2F29-4F60-93AD-EFFB97CC9E20" DisplayName="COM Server" />
  13.           </com:ExeServer>
  14.         </com:ComServer>
  15.       </com:Extension>
  16.     </Extensions>
  17.   </Application>
  18. </Applications>
复制代码
如今我们已经完成了服务端的制作,接下来我们就可以让客户端调用服务器远程类了。
在Factory类继续添加获取远程类的相关内容:
  1. public static partial class Factory
  2. {
  3.     private static bool IsAlive() => true;
  4.     public static IRemoteThing CreateRemoteThing() =>
  5.         CreateInstance<IRemoteThing>(CLSID_IRemoteThing, CLSCTX.CLSCTX_ALL, TimeSpan.FromMinutes(1));
  6.     internal static T CreateInstance<T>(Guid rclsid, CLSCTX dwClsContext = CLSCTX.CLSCTX_INPROC_SERVER)
  7.     {
  8.         int hresult = CoCreateInstance(rclsid, 0, (uint)dwClsContext, CLSID_IUnknown, out nint result);
  9.         if (hresult < 0)
  10.         {
  11.             Marshal.ThrowExceptionForHR(hresult);
  12.         }
  13.         return Marshaler<T>.FromAbi(result);
  14.     }
  15.     internal static T CreateInstance<T>(Guid rclsid, CLSCTX dwClsContext, TimeSpan period) where T : ISetMonitor
  16.     {
  17.         T results = CreateInstance<T>(rclsid, dwClsContext);
  18.         results.SetMonitor(IsAlive, period);
  19.         return results;
  20.     }
  21.     [LibraryImport("api-ms-win-core-com-l1-1-0.dll")]
  22.     private static partial int CoCreateInstance(in Guid rclsid, nint pUnkOuter, uint dwClsContext, in Guid riid, out nint ppv);
  23. }
复制代码
如今我们只需要执行IRemoteThing remote = Factory.CreateRemoteThing();就能获取远程类了。
到这里我们已经完成了 OOP COM 的全部流程,我们想要实现什么内容就可以按照构建服务器管理类的方法来制作 COM 远程类,然后通过在服务器管理类添加一个构造方法来获取这个远程类,如许我们就不需要单独分配 CLSID 和注册 COM 类了。
比如我们可以给Process套个壳:
  1. /// <inheritdoc cref="Process"/>
  2. public partial class RemoteProcess(Process inner) : IProcess
  3. {
  4.     /// <inheritdoc cref="Process.ProcessName"/>
  5.     public string ProcessName => inner.ProcessName;
  6.     /// <inheritdoc cref="Process.StandardError"/>
  7.     public ITextReader StandardError => new RemoteTextReader(inner.StandardError);
  8.     /// <inheritdoc cref="Process.ProcessName"/>
  9.     public ITextWriter StandardInput => new RemoteTextWriter(inner.StandardInput);
  10.     /// <inheritdoc cref="Process.StandardOutput"/>
  11.     public ITextReader StandardOutput => new RemoteTextReader(inner.StandardOutput);
  12.     /// <inheritdoc cref="Process.StartInfo"/>
  13.     public IProcessStartInfo StartInfo
  14.     {
  15.         get => new RemoteProcessStartInfo(inner.StartInfo);
  16.         set => value.ToProcessStartInfo();
  17.     }
  18.     private readonly ConditionalWeakTable<CoDataReceivedEventHandler, DataReceivedEventHandler> errorDataReceived = [];
  19.     /// <inheritdoc cref="Process.ErrorDataReceived"/>
  20.     public event CoDataReceivedEventHandler ErrorDataReceived
  21.     {
  22.         add
  23.         {
  24.             void wrapper(object sender, DataReceivedEventArgs e) => value(this, new CoDataReceivedEventArgs(e.Data));
  25.             DataReceivedEventHandler handler = wrapper;
  26.             inner.ErrorDataReceived += handler;
  27.             errorDataReceived.Add(value, handler);
  28.         }
  29.         remove
  30.         {
  31.             if (errorDataReceived.TryGetValue(value, out DataReceivedEventHandler handler))
  32.             {
  33.                 inner.ErrorDataReceived -= handler;
  34.                 errorDataReceived.Remove(value);
  35.             }
  36.         }
  37.     }
  38.     private readonly ConditionalWeakTable<CoDataReceivedEventHandler, DataReceivedEventHandler> outputDataReceived = [];
  39.     /// <inheritdoc cref="Process.OutputDataReceived"/>
  40.     public event CoDataReceivedEventHandler OutputDataReceived
  41.     {
  42.         add
  43.         {
  44.             void wrapper(object sender, DataReceivedEventArgs e) => value(this, new CoDataReceivedEventArgs(e.Data));
  45.             DataReceivedEventHandler handler = wrapper;
  46.             inner.OutputDataReceived += handler;
  47.             outputDataReceived.Add(value, handler);
  48.         }
  49.         remove
  50.         {
  51.             if (outputDataReceived.TryGetValue(value, out DataReceivedEventHandler handler))
  52.             {
  53.                 inner.OutputDataReceived -= handler;
  54.                 outputDataReceived.Remove(value);
  55.             }
  56.         }
  57.     }
  58.     /// <inheritdoc cref="Process.BeginErrorReadLine"/>
  59.     public void BeginErrorReadLine() => inner.BeginErrorReadLine();
  60.     /// <inheritdoc cref="Process.BeginOutputReadLine"/>
  61.     public void BeginOutputReadLine() => inner.BeginOutputReadLine();
  62.     /// <inheritdoc cref="Process.CancelErrorRead"/>
  63.     public void CancelErrorRead() => inner.CancelErrorRead();
  64.     /// <inheritdoc cref="Process.CancelOutputRead"/>
  65.     public void CancelOutputRead() => inner.CancelOutputRead();
  66.     /// <inheritdoc cref="Component.Dispose"/>
  67.     public void Dispose()
  68.     {
  69.         inner.Dispose();
  70.         GC.SuppressFinalize(this);
  71.     }
  72.     /// <inheritdoc cref="Process.ToString"/>
  73.     public override string ToString() => inner.ToString();
  74. }
复制代码
静态部分可以弄一个假装的静态类:
  1. /// <inheritdoc cref="Process"/>
  2. public sealed partial class ProcessStatic : IProcessStatic
  3. {
  4.     /// <inheritdoc cref="Process.GetProcesses()"/>
  5.     public IProcess[] GetProcesses() => Process.GetProcesses().Select(x => new RemoteProcess(x)).ToArray();
  6.     public IProcess Start(IProcessStartInfo startInfo) =>
  7.         Process.Start(startInfo.ToProcessStartInfo()) is Process process
  8.             ? new RemoteProcess(process) : null;
  9. }
复制代码
然后我们在服务器管理类里增长构造方法:
  1. public IProcessStatic CreateProcessStatic() => new ProcessStatic();
复制代码
如许我们就可以在 UWP 里使用 Process 创建一个 cmd 进程了:
  1. IRemoteThing remote = Factory.CreateRemoteThing();
  2. process = remote.CreateProcessStatic().Start(new RemoteProcessStartInfo
  3. {
  4.     FileName = "cmd",
  5.     CreateNoWindow = true,
  6.     RedirectStandardError = true,
  7.     RedirectStandardInput = true,
  8.     RedirectStandardOutput = true,
  9.     UseShellExecute = false
  10. });
  11. AppTitle.Text = process.ProcessName;
  12. process.OutputDataReceived += OnOutputDataReceived;
  13. process.ErrorDataReceived += OnErrorDataReceived;
  14. process.BeginOutputReadLine();
  15. process.BeginErrorReadLine();
复制代码
具体实现可以查看:SelfCOMServer/SelfCOMServer/Common/RemoteProcess.cs at main · wherewhere/SelfCOMServer

最后附上示例应用:https://github.com/wherewhere/SelfCOMServer

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
继续阅读请点击广告

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

拉不拉稀肚拉稀

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表