简体   繁体   English

将控制台应用程序窗口置于最前面的代码说明

[英]Bring console application window to front code explanation

I need to bring the console from an C# form/console application to the front. 我需要将控制台从C#表单/控制台应用程序移到最前面。 I got the following code which will bring the console window to front from: bring a console window to front in c# 我得到以下代码,它将控制台窗口从前面移到: 在C#中将控制台窗口放在前面

However why does this code example also prints true and how can I disable it? 但是,为什么此代码示例也显示true ,如何禁用它?

public static void ToFront()
{
    string originalTitle = Console.Title;
    string uniqueTitle = Guid.NewGuid().ToString();
    Console.Title = uniqueTitle;
    Thread.Sleep(50);
    IntPtr handle = FindWindowByCaption(IntPtr.Zero, uniqueTitle);
    Console.Title = originalTitle;
    Console.WriteLine(SetForegroundWindow(handle));
}

Change your last line from 从更改最后一行

Console.WriteLine(SetForegroundWindow(handle));

to

SetForegroundWindow(handle);

What you had was executing the function and printing the resulting value. 您执行的功能是打印结果值。

This line is the culprit: 这是罪魁祸首:

Console.WriteLine(SetForegroundWindow(handle));

SetForeGroundWindow returns a bool, which is cast to a string automatically by WriteLine, and printed out. SetForeGroundWindow返回布尔值,该布尔值由WriteLine自动转换为字符串,并打印出来。

Replace it with: 替换为:

SetForegroundWindow(handle);

You are printing out the return of SetForgroundWindow which returns true when it succeeds. 您正在打印SetForgroundWindow的返回值,该返回值在成功时返回true。 Just remove the class to console.writeline 只需将类删除到console.writeline

Console.Title = originalTitle;
SetForegroundWindow(handle);

You can use; 您可以使用;

SetForegroundWindow(handle);

not

Console.WriteLine(SetForegroundWindow(handle));

Given that the title is unique within the desktop, add a reference to Microsoft.VisualBasic, then: 鉴于标题在桌面中是唯一的,请添加对Microsoft.VisualBasic的引用,然后:

using Microsoft.VisualBasic;
....
Interaction.AppActivate(Console.Title);

Edit: Sorry I didn't completely read the question, but this is a simple way of bring an app to the foreground if the VB import doesn't offend you. 编辑:抱歉,我没有完全阅读问题,但是如果VB导入不会冒犯您,这是将应用程序置于前台的一种简单方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM