2

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));
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
H3AP
  • 1,058
  • 1
  • 10
  • 16
  • 1
    The **last line** is responsible for printing "true", you should change it to `SetForegroundWindow(handle)` from `Console.WriteLine(SetForegroundWindow(handle))` . – Nikhil Girraj Apr 09 '13 at 14:12

5 Answers5

4

Change your last line from

Console.WriteLine(SetForegroundWindow(handle));

to

SetForegroundWindow(handle);

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

Ash
  • 369
  • 1
  • 2
  • 13
1

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);
Rassi
  • 1,612
  • 14
  • 21
0

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);
rerun
  • 25,014
  • 6
  • 48
  • 78
0

You can use;

SetForegroundWindow(handle);

not

Console.WriteLine(SetForegroundWindow(handle));
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
0

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.

C.M.
  • 1,474
  • 13
  • 16