H3AP
H3AP

Reputation: 1058

Bring console application window to front code explanation

I need to bring the console from an C# form/console application to the front. I got the following code which will bring the console window to front from: bring a console window to front in c#

However why does this code example also prints true and how can I disable it?

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));
}

Upvotes: 2

Views: 1973

Answers (5)

C.M.
C.M.

Reputation: 1561

Given that the title is unique within the desktop, add a reference to Microsoft.VisualBasic, then:

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.

Upvotes: 0

Soner Gönül
Soner Gönül

Reputation: 98740

You can use;

SetForegroundWindow(handle);

not

Console.WriteLine(SetForegroundWindow(handle));

Upvotes: 0

Rassi
Rassi

Reputation: 1622

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.

Replace it with:

SetForegroundWindow(handle);

Upvotes: 1

Ash
Ash

Reputation: 389

Change your last line from

Console.WriteLine(SetForegroundWindow(handle));

to

SetForegroundWindow(handle);

What you had was executing the function and printing the resulting value.

Upvotes: 4

rerun
rerun

Reputation: 25495

You are printing out the return of SetForgroundWindow which returns true when it succeeds. Just remove the class to console.writeline

Console.Title = originalTitle;
SetForegroundWindow(handle);

Upvotes: 0

Related Questions