Hide icon in tray windows - c#

I use a component in my C # application it loads the DLL, an icon appeared in the windows tray, is there any way to hide the icon in tray using the command line or any exe with arguments?
Thanks.

From the command line IMHO its not possible unless the exe supports it, eg:
static void Main(string[] args)
{
if (args.Length > 0)
{
if (args[0] == "HideFromWindowsTray")
{
this.ShowInTaskBar = false;
}
}
You could possibly do it using other techniques, eg have a wrapper exe that launches a exe and sets its ShowInTaskBar form property to False. To get inspiration on how you can do this, see HawkEye - The .Net Runtime Object Editor
ps next to each answer is a holo checkbox, tick it to accept answer and you'll get points too.

Related

How to check a Window already opened when button is clicked?

I am Working in Visual Studio 2008 Winforms Application project in Windows 7 (32 bit).I am doing the project in C#.
I have placed some buttons in a tab and added actions for that once it is clicked. While clicking the button am just running a .exe file in its action part.
My problem is that, i opened a window by clicking one button(so the .exe file is running), now while am clicking the button again it is opening same window again irrespective of checking that it is open or not. I want to solve this issue,as when a window is opened it must not open again on another click on same button. How to solve this issue. ?
Please help....
Thanks in advance..
You could check if the process is already running, when re-clicking the button:
private void btnStartExecutable_Click(object sender, EventArgs e)
{
Process[] processName = Process.GetProcessesByName("InsertProcessNameHere");
if (pname.Length == 0)
{
MessageBox.Show("Application isn't running yet.");
//Start application here
Process.Start("InsertProcessNameHere");
}
else
{
MessageBox.Show("Application is already running.");
//Don't start application, since it has been started already
}
}
You can try this:
bool processExited = true;
private void button1_Click(object sender, EventArgs e)
{
if (processExited)
{
Process process = new Process();
process.EnableRaisingEvents = true;
process.Exited += MyProcessExited;
process.StartInfo = new ProcessStartInfo();
process.StartInfo.FileName = "notepad.exe";
process.Start();
processExited = false;
}
else
{
MessageBox.Show("Still running");
}
}
void MyProcessExited(object sender, EventArgs e)
{
processExited = true;
}
The right answer here IMHO is that unless the two application shares a common resource or can talk to each other through some channel, there is no safe and efficient way to achieve what you want. Since the process is external, it could already be running before your calling app starts, or even while it's already running. You won't be able to tell if the process has been started from your app or not.
By the time I'm writing this your question does not yet state if you are in liberty to modify the external app you are calling. If you are however, using a Mutex would be a quick and easy way to solve your problem.
In your external app, whenever you want to make the other app aware of whatever condition you want (be it that the process is running or that a specific window is opened), have a Mutex instance created like this:
var mutex = new Threading.Mutex(true, "mutex unique identifier");
And in your calling app, try to create a Mutex instance with the same identifier:
bool alreadyExists;
var mutex = new Threading.Mutex(false, "mutex unique identifier", out alreadyExists);
Here the alreadyExists variable will tell you whether or not the external process is running or not. This is much safer than trying to identify it via its name, as other processes could have the same or a new version could be of a different name. Of course, the mutex identifier must be as unique as possible (like a Guid), otherwise you may encounter the same problem. ;)
Whenever you feel like the mutex must be released (at external app level), release it:
mutex.ReleaseMutex();
Note that if the process ends the mutex will be automatically released by the OS.
If the external app isn't a .NET based app, you can still create a mutex with Win32 API functions.
Thanks for the support.. I got the answer like this..
1) Creating an event'Exit' for the process in function button click
2) Define a function for the exit event where you set a flag
3) Check the flag is set or not everytime while opening the process in the function button click
Event for Exit: 'P' is the name of process:
p.Exited += new EventHandler(p_Exited);
p_Exited will be the function name where we will set the flag.
Thanks all...
If you know the name of the process that gets started or the path the .exe is run from you can use the Process class to check to see if it is currently running.
http://msdn.microsoft.com/en-us/library/system.diagnostics.process(v=vs.110).aspx

How to close Internet Explorer when it has been ran with Process.Start?

I'm have a WPF application that is starting Internet explorer (Version 9, on Win7 X64) using Process.Start method.
I save the ProcessID in order to close it when the application is closed. However, when the application exits, the Internet Explorer is still visible in the task manager.
Here is the code I'm using :
public class MyClass : IDisposable
{
Process _process;
public void Go()
{
ProcessStartInfo psi = new ProcessStartInfo {
FileName = "iexplore.exe",
Arguments = "-noframemerging -private \"http://whathaveyoutried.com\""
};
_process = Process.Start(psi);
_process.WaitForInputIdle();
}
private void Close(object sender, RoutedEventArgs e)
{
if (_process != null)
{
_process.Refresh();
_process.Close();
}
}
public void Dispose()
{
if (_process != null)
{
_process.Refresh();
_process.Close();
}
}
}
}
I double checked, the call to _process.Close() is actually done.
What can cause this behavior?
PS: I'm suspecting this is due to Internet Explorer internal. Running the exe won't necessary create a new process, but can use some IPC to control other instances. I use the -noframemerging command line argument, but it does not look to solve the issue.
[Edit] This is the continuation of another question I asked few days ago. Actually, I'm Pinvoking SetParent function to embbed the spawned IE in my application. I can't use the WebBrowser control because it does not support the isolation I'm looking for. So it's OK to close IE when my app closes.
Every tab of Internet Explorer is a process. If you open IE with multiple tabs or user opens another tabs, it won't be enough to kill process.
But
_process.Close();
Frees all resources belongs to _process. You can use _process.Kill() method instead of it.
For better security and stability, IE8 uses the Loosely Coupled Internet Explorer (LCIE) architecture and runs the browser frame and tabs in separate processes. LCIE prevents glitches and hangs from bringing down the entire browser and leads to higher performance and scalability. I read this on Wikipedia.
You can disable LCIE, but I am not sure why you would want to do that. I would consider using the a solution that #Damien_The_Unbeliever mention above.
I have an IE application in my win32 Application and i'm using Win32Api - SendMessage with WM_CLOSE = 0x0010
SendMessage(handle,0x0010,IntPtr.Zero, IntPtr.Zero)}
This closes the IE, how ever you need to have the specific handle of the Browser (Class IEFrame).
There is one drawback, in case you have more then one tab, the IE opens confirm close dialog which prevent the close process.
One way to overcome the dialog opening is to set it check box to (always close), but for me itţs not an option.

Execute process/program silently

I am creating a wpf application that needs a prerequisite. If that prerequisites is not met then I ask the user if he will like to install the prerequisite that happens to be: Microsoft Visual C++ 2010 SP1 Redistributable Package.
So if the user chose to install the prerequisite I will execute vcredist_x86.exe (that is the file that get's downloaded from the first link that I provided).
Then on my application I will be able to tell when the installation is complete by doing something like:
ProcessStartInfo psi = new ProcessStartInfo(#"vcredist_x86.exe");
var p = new Process(); p.StartInfo = psi;
p.Start(); //start the process
p.WaitForExit(); // wait for the installation to finish
// installation should be done now
Ok everything works great so far. The problem is that I have a progress bar in my wpf application and I will like to show the progress in there.
I have been able to show the progress of the installation by doing the following:
There is a program called AutoIt that it is great for automating simple tasks. For example I can easily detect if a window exists with autoit by using something like:
I could then compile that script and create a very small executable. In that executable I will return 1 if the specified window exists or 0 otherwise.
When the user moves to the next window my script might return 2 because that is a different window. AutoIt can also see the progress of a progress bar of a window!!! so if that script returns 80 for example then I will update my progress to 80% for instance.
I do that by doing something like:
// start the autoitExecutable....
// wait for executable to exit usually takes 10 miliseconds it is fast
if (autoitProcess.ExitCode == 1)
{
// do somthing
}else if(autoitProcess.ExitCode == 2)
{
// do something else
} //etc....
As you can see I have to execute that script every 1 second to detect what changes have been done in order to update my progress bar in WPF. That works but every time I execute that executable with c# I get the:
cursor for about 500 milliseconds then on the next second it appears again. That becomes annoying even though no windows show up. It will be nice if I could get rid of that cursor and execute that executable silently somehow. when I execute the autoit executable there are no windows that show up nor nothing else.
P.S.
I know I could use c# to check for the existance of a window and maybe see the value of other window's handler's just like autoit is able to do it but it is so simple to create those programs with AutoIt and it will be nice if I could use AutoIt instead of C# for this kind of taks
I saw this behavior when the exe was set to "windows application" rather than "console application".
Changing the type to console no longer gives a busy cursor at launch.
You could add an event handler as well for example
System.Diagnostics.ProcessStartInfo p = new
System.Diagnostics.ProcessStartInfo(#"vcredist_x86.exe") ;
p.Arguments="-RunForever";
proc = new System.Diagnostics.Process();
proc.StartInfo = p;
proc.EnableRaisingEvents = true;
proc.Exited += new EventHandler(myProcess_Exited);
proc.Start();
inside the event if I wanted to do something like this
// Inside the form class:
private System.Diagnostics.Process proc;
private void myProcess_Exited(object sender, System.EventArgs e)
{
button3.BackColor=Color.LightGreen; //success indicator
}
if you wanted to do this in a While Loop you could also do something like this for example
but you would have to change the params to fit your case
example code you can utilize
while(!autoitProcess.WaitForExit(someTimeout))
{
if(ShouldCancel)
{
break;
}
}
does this make sense or help out...?

C# - Minimize to tray at system startup

In my application, I have an option to start the application when Windows is started. That works great. I also have it so that, when minimized, the application is minimized to the system tray. Is there a way that I could have it be automatically minimized when started up at the same time as Windows? The only way I could think of, is to retrieve the amount of time that they system has been on and use that data to decide whether the machine had recently started. Obviously there are a lot of flaws with that theory. Anybody have any other ideas as to how this could be done?
Implement a command line switch in your program that causes your program to minimize to the tray. When you start the program with Windows startup, just include the switch.
http://msdn.microsoft.com/en-us/library/acy3edy3.aspx
In your Form "Properties" in WindowState change to "Minimized", or in code:
//After this:
InitializeComponent();
//Place this line:
WindowState = FormWindowState.Minimized;
Hope this help!
Use a command line argument, e.g. /startminimised. In your app check for the presence of this switch (using Environment.GetCommandLineArgs) when the app starts, and automatically minimise if the switch is present.
Then in your "run on startup" option, ensure that the app is started with this switch e.g. set the Run registry key or Startup group shortcut to myapp.exe /startminimised.
When the user runs your app, however, they won't (normally!) specify the switch, so the app will appear as a window.
You can call your program with a parameter, for example "-minimized" and then handle that parameter in your program:
In your program.cs, handle the parameter, and then pass that parameter to Form1:
static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
if (args.Length != 0){
Application.Run(new Form1(args[0]));
}
else
{
Application.Run(new Form1("normalState"));
}
}
In your Form1.cs, you can call a function with the passed parameter and minimize the app:
public Form1(string parameter)
{
InitializeComponent();
SetStartup(); //This function will set your app in the registry to run on startup. I'll explain this function below.
MinimizeApp(parameter);
}
For example, with this function i used, if you start the application with the -minimized parameter, then it will start minimized, a notifyicon pops up in the taskbar and a bubble saying the app is started and running in the background.
public void MinimizeApp(string parameter)
{
if (parameter == "-minimized")
{
this.WindowState = FormWindowState.Minimized;
notifyIcon1.Visible = true;
notifyIcon1.BalloonTipText = "Program is started and running in the background...";
notifyIcon1.ShowBalloonTip(500);
Hide();
}
}
The SetStartup function puts your program into the registry, so it'll run on startup.
private void SetStartup(){
Microsoft.Win32.RegistryKey key;
key = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(#"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
key.SetValue(AppName, Application.ExecutablePath.ToString());
string ApplicationPath = "\"" + Application.ExecutablePath.ToString() + "\" -minimized";
key.SetValue("MyApplicationName", ApplicationPath);
key.Close();
}
Right now, when you start your program with -minimized parameter, for example: "c:/programs/app.exe" -minimized then it will start minimized, and when you restart your computer, it also starts automatically minimized.

how to run a winform from console application?

How do I create, execute and control a winform from within a console application?
The easiest option is to start a windows forms project, then change the output-type to Console Application. Alternatively, just add a reference to System.Windows.Forms.dll, and start coding:
using System.Windows.Forms;
[STAThread]
static void Main() {
Application.EnableVisualStyles();
Application.Run(new Form()); // or whatever
}
The important bit is the [STAThread] on your Main() method, required for full COM support.
I recently wanted to do this and found that I was not happy with any of the answers here.
If you follow Marc's advice and set the output-type to Console Application there are two problems:
1) If you launch the application from Explorer, you get an annoying console window behind your Form which doesn't go away until your program exits. We can mitigate this problem by calling FreeConsole prior to showing the GUI (Application.Run). The annoyance here is that the console window still appears. It immediately goes away, but is there for a moment none-the-less.
2) If you launch it from a console, and display a GUI, the console is blocked until the GUI exits. This is because the console (cmd.exe) thinks it should launch Console apps synchronously and Windows apps asynchronously (the unix equivalent of "myprocess &").
If you leave the output-type as Windows Application, but correctly call AttachConsole, you don't get a second console window when invoked from a console and you don't get the unnecessary console when invoked from Explorer. The correct way to call AttachConsole is to pass -1 to it. This causes our process to attach to the console of our parent process (the console window that launched us).
However, this has two different problems:
1) Because the console launches Windows apps in the background, it immediately displays the prompt and allows further input. On the one hand this is good news, the console is not blocked on your GUI app, but in the case where you want to dump output to the console and never show the GUI, your program's output comes after the prompt and no new prompt is displayed when you're done. This looks a bit confusing, not to mention that your "console app" is running in the background and the user is free to execute other commands while it's running.
2) Stream redirection gets messed up as well, e.g. "myapp some parameters > somefile" fails to redirect. The stream redirection problem requires a significant amount of p/Invoke to fixup the standard handles, but it is solvable.
After many hours of hunting and experimenting, I've come to the conclusion that there is no way to do this perfectly. You simply cannot get all the benefits of both console and window without any side effects. It's a matter of picking which side effects are least annoying for your application's purposes.
Here is the best method that I've found:
First, set your projects output type to "Windows Application", then P/Invoke AllocConsole to create a console window.
internal static class NativeMethods
{
[DllImport("kernel32.dll")]
internal static extern Boolean AllocConsole();
}
static class Program
{
static void Main(string[] args) {
if (args.Length == 0) {
// run as windows app
Application.EnableVisualStyles();
Application.Run(new Form1());
} else {
// run as console app
NativeMethods.AllocConsole();
Console.WriteLine("Hello World");
Console.ReadLine();
}
}
}
It´s very simple to do:
Just add following attribute and code to your Main-method:
[STAThread]
void Main(string[] args])
{
Application.EnableVisualStyles();
//Do some stuff...
while(!Exit)
{
Application.DoEvents(); //Now if you call "form.Show()" your form won´t be frozen
//Do your stuff
}
}
Now you´re fully able to show WinForms :)
You can create a winform project in VS2005/ VS2008 and then change its properties to be a command line application. It can then be started from the command line, but will still open a winform.
All the above answers are great help, but I thought to add some more tips for the absolute beginner.
So, you want to do something with Windows Forms, in a Console Application:
Add a reference to System.Windows.Forms.dll in your Console application project in Solution Explorer. (Right Click on Solution-name->add->Reference...)
Specify the name space in code: using System.Windows.Forms;
Declare the needed properties in your class for the controls you wish to add to the form.
e.g. int Left { get; set; } // need to specify the LEFT position of the button on the Form
And then add the following code snippet in Main():
static void Main(string[] args)
{
Application.EnableVisualStyles();
Form frm = new Form(); // create aForm object
Button btn = new Button()
{
Left = 120,
Width = 130,
Height = 30,
Top = 150,
Text = "Biju Joseph, Redmond, WA"
};
//… more code
frm.Controls.Add(btn); // add button to the Form
// …. add more code here as needed
frm.ShowDialog(); // a modal dialog
}
This worked for my needs...
Task mytask = Task.Run(() =>
{
MyForm form = new MyForm();
form.ShowDialog();
});
This starts the from in a new thread and does not release the thread until the form is closed. Task is in .Net 4 and later.
You should be able to use the Application class in the same way as Winform apps do. Probably the easiest way to start a new project is to do what Marc suggested: create a new Winform project, and then change it in the options to a console application
Its totally depends upon your choice, that how you are implementing.
a. Attached process , ex: input on form and print on console
b. Independent process, ex: start a timer, don't close even if console exit.
for a,
Application.Run(new Form1());
//or -------------
Form1 f = new Form1();
f.ShowDialog();
for b,
Use thread, or task anything,
How to open win form independently?
If you want to escape from Form Freeze and use editing (like text for a button) use this code
Form form = new Form();
Form.Button.Text = "randomText";
System.Windows.Forms.Application.EnableVisualStyles();
System.Windows.Forms.Application.Run(form);

Categories

Resources