I'm working with windows form and i have a main form and when I click on some button he open a console window that do some work and when its done I want to close the console without closing the all application (main form). I try to close the console with Environment.Exit(1) or the function Destroy() that belongs to the Destroy() and Create() the console window. the Environment.Exit(1) and Destroy() both close the console but close the form too.
I wonder if there is a way to close only the console without closing the whole application
EDIT
private void btSync_Click(object sender, EventArgs e)
{
Create();
ServerSync sycs=new ServerSync();
Thread sync = new Thread(new ThreadStart(sycs.run));
sync.Start();
}
The Create() open a Console window that run a Socket() Thread.
Problem Solved
When im start the thread i add to the end of code a ThreadName.Abort and outside the thread i check if ThreadName.IsAlived==false and inside the if i Hide() the console and then Destroy() And Its Works!
the Hide() method from AppDeveloper answer.
Thanks for your help!
Instead of using Environment.Exit() hide the Console Window
using System.Runtime.InteropServices;
[DllImport("kernel32.dll")]
static extern IntPtr GetConsoleWindow();
[DllImport("user32.dll")]
static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
const int SW_HIDE = 0x0;
const int SW_SHOW = 0x5;
public static void HideConsoleWindow()
{
var handle = GetConsoleWindow();
ShowWindow(handle, SW_HIDE);
}
Maybe there is a console.hide() option? could try that out.
Related
I use this code to check whether my program is already open:
string RunningProcess = System.Diagnostics.Process.GetCurrentProcess().ProcessName;
System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcessesByName(RunningProcess);
if (processes.Length > 1)
{ return true; }
It would, if the program is open, bring it to the floor and show it. How can I do? Thank you.
You have to import the following method:
[DllImport("user32.dll")]
static extern bool ShowWindow(IntPtr hwnd, int nCmdShow);
Then you can call this method this way:
ShowWindow(process.MainWindowHandle, 0);//Hide
ShowWindow(process.MainWindowHandle, 1);//Show
NOTE: The window can just be shown if it is minimized. It won't show it if it is in the background of an other window.
If you want to show a window that is in the background of an other one you have to import this method:
[DllImport("user32.dll")]
static extern bool SetForegroundWindow(IntPtr hWnd);
Then call it in the same way as ShowWindow:
SetForegroundWindow(process.MainWindowHandle);
NOTE: You can just set the foreground window if it is not minimized.
You can also combine both methods with IsIconic to call the right method:
[DllImport("user32.dll")]
static extern bool IsIconic(IntPtr hWnd);//Returns false if the window is minimized
The full code to show the mainwindow:
static void GotoProcess(Process process)
{
if (IsIconic(process.MainWindowHandle))
{
ShowWindow(process.MainWindowHandle, 1);
}
else
{
SetForegroundWindow(process.MainWindowHandle);
}
}
This question already has answers here:
Show/Hide the console window of a C# console application
(9 answers)
Closed 7 years ago.
I have an application that was using the console, but I changed all the code to write to a file instead of the console. I would now like the console to stop appearing when I run the application. How do I do this? I do not know what is opening the console in the first place, even though nothing is being written to it in the code.
I have looked in the applications references and cannot find System.Console being referenced. I though disabling that would fix it or point me in the right direction with errors. I am not sure where else to look.
All the other things I found online talk about making the console hidden. I would like it to not appear in the first place.
Go to the Application Properties and change Output Type from Console Application to Windows Application.
Or you can do it using a code below
using System.Runtime.InteropServices;
[DllImport("kernel32.dll")]
static extern IntPtr GetConsoleWindow();
[DllImport("user32.dll")]
static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
And in main
const int SW_HIDE = 0;
const int SW_SHOW = 5;
var handle = GetConsoleWindow();
ShowWindow(handle, SW_HIDE); // To hide
ShowWindow(handle, SW_SHOW); // To show
Also, you can run you application as a service. In order to do this you should create a service - File->New Project->Visual C#->Windows->Windows Service. Then create a public method StartWork() and add all you logic there. And call this method in OnStart().
protected override void OnStart(string[] args)
{
try
{
this.StartJobs();
}
catch (Exception ex)
{
// catching exception
}
}
public void StartWork()
{
// all the logic here
}
In main you should create this service and use System.ServiceProcess.ServiceBase.Run() to run it as service or call StartWork() to run it as console application.
static void Main(string[] args)
{
TestService = new TestService ();
#if DEBUG
TestService.StartWork()();
#else
System.ServiceProcess.ServiceBase.Run(TestService );
#endif
}
I want to hide a window that is created when I call p.Start(). The code I have now does work but my program freezes for about 20-40 seconds because of the while loop that is in there.
Current code:
[System.Runtime.InteropServices.DllImport("user32.dll")]
static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
const int SW_HIDE = 0;
//Process p is already created and initialized
p.Start();
while(p.MainWindowHandle == IntPtr.Zero)
{
p.Refresh();
}
ShowWindow(p.MainWindowHandle, SW_HIDE);
Removing the while loop prevents the freezing of my program, but the window doesn't hide then. I did do p.StartInfo.CreateNoWindow = true, but this only works for console windows.
So, my question is: How can I hide a window created by a process without it freezes my program for 20 seconds
Can you try to put this code:
while(p.MainWindowHandle == IntPtr.Zero)
{
p.Refresh();
}
ShowWindow(p.MainWindowHandle, SW_HIDE);
in task and run it? It should remove the program freezing.
I want to create a software like a virtualkeyboard, you have a AlwaysTop Window and use this to put some data on another process/windows. In this case I will record all data on clipboard and compare if this data is compatible with a pattern (A### is the patern and A123 is compatible with the patern), if yes the application will put it in a listbox and the user can paste it on another process/windows (already open) clicking on item on list.
My question is about how to put this information on the last application/process used, I already started a prototype of code but the line indicated is wrong, on my code it's the currentprocess and need to be the last used before click on my form.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
[DllImport("user32.dll")]
static extern IntPtr SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]
internal static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
[DllImport("User32.dll")]
static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
private void button2_Click(object sender, EventArgs e)
{
Process currentProcess = Process.GetCurrentProcess(); //this line is wrong
IntPtr hWnd = currentProcess.MainWindowHandle; //this line is wrong
if (hWnd != IntPtr.Zero)
{
SetForegroundWindow(hWnd);
ShowWindow(hWnd, 9);
SendKeys.Send("A123");
}
}
}
}
I get on simple solution, instead of get the process I just send the combination ALT+TAB and work for all cases that I need. Below the solution if anyone need in the future:
string old_clipboard = Clipboard.GetText();
Clipboard.SetText("A123");
SendKeys.SendWait("%{Tab}");
SendKeys.SendWait("^V");
Thread.Sleep(100);
Clipboard.SetText(old_clipboard);
Ps.: I put one delay because the SendWait works only on caller windows, as the target of ^V is another process it´s don´t work well.
Best regards. =)
I have a GUI app written with C# that must be hidden off the screen when it starts (instead, it displays a tray icon.) In C++/MFC I'd hide it as such:
void OnWindowPosChanging(WINDOWPOS* lpwndpos)
{
CDialog::OnWindowPosChanging(lpwndpos);
//Prevent dialog from showing
lpwndpos->flags &= ~SWP_SHOWWINDOW;
}
But is there an easier way in C#?
You will need to set the form's Visible and ShowInTaskbar properties to false and then simply use the NotifyIcon class to show an icon in the tray area.
Alternative if this will be the first form your application will open you will need to edit the Application.Run() in your Program.cs file.
Simply replace
Application.Run(new MyForm());
with
MyForm myForm = new MyForm();
Application.Run();
Then in your form's constructor initialize the NotifyIcon object.
NotifyIcon nIcon = new NotifyIcon();
nIcon.Icon = new Icon(#"...");
nIcon.Visible = true;
You do this in Winforms by overriding the SetVisibleCore() method in your form. Some extra work is required, the native window gets created in traditional .NET lazy fashion. The trigger is the first Show() call. So you still have to ensure that this is taken care of. Paste this code into your form:
protected override void SetVisibleCore(bool value) {
if (!this.IsHandleCreated) {
value = false;
this.CreateHandle();
}
base.SetVisibleCore(value);
}
You can now make it visible whenever you are ready to by calling Show() or setting the Visible property to true. Do beware that the Load event doesn't fire until then so be sure to move all initialization code into the constructor, where it belongs.
You can use the ShowInTaskBar and Visible property of the startup form.
I used this to hide a console window, (eventually).
private static class NativeMethods
{
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
public static void SetConsoleWindowVisibility(Boolean argShow)
{
IntPtr hWnd = NativeMethods.FindWindow(null, Console.Title);
if (hWnd != IntPtr.Zero)
{
if (!argShow)
//Hide the window
ShowWindow(hWnd, 0); // 0 = SW_HIDE
else
//Show window again
ShowWindow(hWnd, 1); //1 = SW_SHOWNORMAL
}
}
}
All looks a bit complicated, but's it's basically get a handle to the window and then call ShowWindow with it. As it's a console app, I pass in a command line argument to not hide the window, for debugging and such.
I put this in program.cs, decode the command line args and then just call NativeMethods.SetConsoleWindowVisiblity.
Never did find out why just setting visibility and showintaskbar didn't work. But they definitely didn't