如何通过C#最小化远程桌面连接(RDC)窗口?

3
以下代码片段可通过mstsc.exe帮助我与计算机建立远程桌面连接。
 string ipAddress = "XXX.XX.XXX.XXX" // IP Address of other machine
 System.Diagnostics.Process proc = new System.Diagnostics.Process();
 proc.StartInfo.UseShellExecute = true;
 proc.StartInfo.FileName = "mstsc.exe";
 proc.StartInfo.Arguments = "/v:" + ipAddress ;    
 proc.Start();

一旦成功启动RDC窗口(镜像窗口),我想将其最小化。这里有没有通过C#实现它的方法?

这是我尝试过的,但效果不明显:

proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;

任何帮助都将不胜感激。
2个回答

2
您可以使用来自user32.dllShowWindow函数。将以下导入添加到您的程序中。 您需要引用using System.Runtime.InteropServices;
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

您已经拥有的启动RDP所需的内容将按原样工作,但然后您需要获取远程桌面打开后创建的新mstsc进程。在proc.Start()之后,您启动的原始进程将退出。使用下面的代码将为您获取第一个mstsc进程。注意:如果您打开了多个RDP窗口,则应该选择更好的方法而不仅仅是选择第一个。
Process process = Process.GetProcessesByName("mstsc").First();

然后使用以下代码调用ShowWindow方法,其中SW_MINIMIZE = 6
ShowWindow(process.MainWindowHandle, SW_MINIMIZE);

完整的解决方案如下:
private const int SW_MAXIMIZE = 3;
private const int SW_MINIMIZE = 6;

[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

static void Main(string[] args) {
    string ipAddress = "xxx.xxx.xxx.xxx";
    Process proc = new Process();
    proc.StartInfo.UseShellExecute = true;
    proc.StartInfo.FileName = "mstsc.exe";
    proc.StartInfo.Arguments = "/v:" + ipAddress ;    
    proc.Start();

    // NOTE: add some kind of delay to wait for the new process to be created.

    Process process = Process.GetProcessesByName("mstsc").First();

    ShowWindow(process.MainWindowHandle, SW_MINIMIZE);
}

注意:@Sergio的答案是可行的,但它会最小化创建的初始进程。如果您需要输入凭据,我认为这不是正确的方法。
参考:ShowWindow函数的参考资料

我尝试了你的解决方案,但仍然无法最小化RDP镜像窗口。 - DotNetSpartan
@user42067,你所说的RDP镜像窗口是什么意思?在新进程创建期间,你是否添加了适当的延迟等待时间? - ivcubr
启动并让用户看到计算机的窗口。我的意思是顶部有三个符号(网络符号、锁定、固定/取消固定)和计算机名称的窗口。我想通过C#最小化该窗口。 - DotNetSpartan
@user42067,在proc.Start();结束和下一行代码之间,你等待的时间足够了吗?请注意我的提示,需要等待新进程被创建。 - ivcubr
@user42067,这肯定是有效的,在我的环境中,Thread.Sleep(10000);就足够了。我在答案中没有指定等待的方式,因为我不太了解你的应用程序。另一种方法是监视mstsc进程的数量,并等待创建新的进程。这将是我认为最干净的解决方案,但这取决于你的实现。 - ivcubr

-1

使用Windows风格,这样可以正常工作。

    string ipAddress = "xxx.xx.xxx.xxx"; // IP Address of other machine
    ProcessStartInfo p = new ProcessStartInfo("mstsc.exe");
    p.UseShellExecute = true;
    p.Arguments = "/v:" + ipAddress;
    p.WindowStyle = ProcessWindowStyle.Minimized;
    Process.Start(p);

1
该进程以最小化的方式启动,然后根据您的要求工作并响应。如果您没有保存的凭据,则会打开一个窗口要求您输入它们,在这种情况下,您是正确的@ivcubr。无论如何,我不明白为什么您会给试图帮助您的人一个负面评分。 - Sergio
抱歉给你的回答打了负分,请修改一下,这样我就可以给你点赞了。虽然你的回答对我没有帮助,但还是谢谢你的帮忙。 - DotNetSpartan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接