How to start the application directly in system tray? (.NET C#) - c#

I mean when the user starts my application(exe). I want it to start directly in system tray, without showing the window. Like antivirus softwares & download managers, which start and run in the system tray silently.
I want the same effect and when user click the "show" button of the notifyIcon's contextmenustrip then only application should show GUI.
I'm using this, but its not working
private void Form_Load(object sender, EventArgs e)
{
this.Hide();
}
May be I need to have Main() function in some other class which has no GUI but has notifyIcon & ContextMenuStrip whose option will instantiate the GUI window class. Right?

The way I usually setup something like this is to modify the Program.cs to look something like the following:
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
using (NotifyIcon icon = new NotifyIcon())
{
icon.Icon = System.Drawing.Icon.ExtractAssociatedIcon(Application.ExecutablePath);
icon.ContextMenu = new ContextMenu(new MenuItem[] {
new MenuItem("Show form", (s, e) => {new Form1().Show();}),
new MenuItem("Exit", (s, e) => { Application.Exit(); }),
});
icon.Visible = true;
Application.Run();
icon.Visible = false;
}
}
Using this, you don't need to worry about hiding instead of closing forms and all the rest of the hacks that can lead to... You can make a singleton form too instead of instantiating a new Form every time you click the show form option. This is something to build off of, not the end solution.

You need to set up the notify icon as well.
Either manually or via the toolbar (drag a notifyIcon onto your form) create the notifyIcon:
this.notifyIcon = new System.Windows.Forms.NotifyIcon(components);
Then add this code to Form_Load():
// Notify icon set up
notifyIcon.Visible = true;
notifyIcon.Text = "Tooltip message here";
this.ShowInTaskbar = false;
this.Hide();
Though this will, as has been pointed out, briefly show the form before hiding it.
From the accepted answer of this question, the solution appears to be to change:
Application.Run(new Form1());
to:
Form1 f = new Form1();
Application.Run();
in Main().

Have you created a Windows Application in C#?
You need to drag a NotifyIcon control onto the form, the control will be placed below the form because it has no visual representation on the form itself.
Then you set its properties such as the Icon...
Try this one first...

Related

Bring main application form in front

i am working on compact framework 3.5, with this issue.ScanOutMenu is a form with two buttons and only in this screen BringToFront() is not working.In all other screen i have input field where it got focus and BringToFront() take the form in front.
private void menuItem1_Click(object sender, EventArgs e)
{
this.Close();
ScanOutMenu scanOutMenu = new ScanOutMenu();
scanOutMenu.BringToFront();
}
Also I tried scanOutMenu.TopMost = true; which is also not working.I think since ScanOutMenu form don't have input field and no focus BringToFront() is not working.
ScanOutMenu form is the main application form and i need to bring the screen in front without using scanOutMenu.Show() or scanOutMenu.ShowDialog()
Have you tried Enabling the TopMost Property?
this.TopMost = true;
//then if you want to remove it just put to false
Sooner or later, when working on a CE app, you have to get your hands dirty with Windows API calls. SetForegroundWindow may do what you're after
// Import the API call
[DllImport("coredll.dll")]
public static extern bool SetForegroundWindow(IntPtr hWnd);
// Then, in your code somewhere
SetForegroundWindow(scanOutMenu.Handle);
See API docs here: http://msdn.microsoft.com/en-us/library/ms940024.aspx
If you already have it open then you need to bring to front the Object that is open.
In the example you show you are bringing to front a object that has not been shown yet.
ScanOutMenu scanOutMenu = new ScanOutMenu(); // Creates a new object
scanOutMenu.BringToFront(); //Brings to front the Object that is not shown.
So to open it you have to make a non-local variable with the Form you want and assign that variable the Form you want to open.
Example:
class test{
AnotherForm op;
public test(){
AnotherForm nForm = new AnotherForm(); //Starts a form object
op = nForm; // Assigns the form to be shown to the non-local variable
nForm.Show(); // shows the form object to user
}
private void menuItem1_Click(object sender, EventArgs e)
{
op.BringToFront(); //This will work
}
}

Windows Application That Displays Pop-Ups While Other Programs Are Running

Firstly, I have zero experience programming with .NET so this could be a pretty nooby question...
I'm wondering if it's possible to build an application like xFire - which displays pop-ups in-game to a user.
As the primary application will have focus, how does my application manage to display it's message/popup? Does the primary application have to allow access or something?
Cheers!
Looks like you are looking for NotifyIcon, it displays little pop-ups just as know from Windows.
The example is a little long, but the documentation will surely help you understand.
using System;
using System.Drawing;
using System.Windows.Forms;
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.NotifyIcon notifyIcon1;
private System.Windows.Forms.ContextMenu contextMenu1;
private System.Windows.Forms.MenuItem menuItem1;
private System.ComponentModel.IContainer components;
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
public Form1()
{
this.components = new System.ComponentModel.Container();
this.contextMenu1 = new System.Windows.Forms.ContextMenu();
this.menuItem1 = new System.Windows.Forms.MenuItem();
// Initialize contextMenu1
this.contextMenu1.MenuItems.AddRange(
new System.Windows.Forms.MenuItem[] {this.menuItem1});
// Initialize menuItem1
this.menuItem1.Index = 0;
this.menuItem1.Text = "E&xit";
this.menuItem1.Click += new System.EventHandler(this.menuItem1_Click);
// Set up how the form should be displayed.
this.ClientSize = new System.Drawing.Size(292, 266);
this.Text = "Notify Icon Example";
// Create the NotifyIcon.
this.notifyIcon1 = new System.Windows.Forms.NotifyIcon(this.components);
// The Icon property sets the icon that will appear
// in the systray for this application.
notifyIcon1.Icon = new Icon("appicon.ico");
// The ContextMenu property sets the menu that will
// appear when the systray icon is right clicked.
notifyIcon1.ContextMenu = this.contextMenu1;
// The Text property sets the text that will be displayed,
// in a tooltip, when the mouse hovers over the systray icon.
notifyIcon1.Text = "Form1 (NotifyIcon example)";
notifyIcon1.Visible = true;
// Handle the DoubleClick event to activate the form.
notifyIcon1.DoubleClick += new System.EventHandler(this.notifyIcon1_DoubleClick);
}
protected override void Dispose( bool disposing )
{
// Clean up any components being used.
if( disposing )
if (components != null)
components.Dispose();
base.Dispose( disposing );
}
private void notifyIcon1_DoubleClick(object Sender, EventArgs e)
{
// Show the form when the user double clicks on the notify icon.
// Set the WindowState to normal if the form is minimized.
if (this.WindowState == FormWindowState.Minimized)
this.WindowState = FormWindowState.Normal;
// Activate the form.
this.Activate();
}
private void menuItem1_Click(object Sender, EventArgs e) {
// Close the form, which closes the application.
this.Close();
}
}
See MSDN.
"As the primary application will have focus, how does my application manage to display it's message/popup? Does the primary application have to allow access or something?"
An application can set itself as "TopMost" which means it appears in front of other "normal" applications that are not TopMost. A well behaved notification will appear without stealing focus from the current application (this is usually achieved with the ShowWindow() API and the SW_SHOWNA flag). This does not require any permission from the currently active application.
Take a look at TaskbarNotifier, a skinnable MSN Messenger-like popup in C# and now in VB.NET too.

opening a window form from another form programmatically

I am making a Windows Forms application. I have a form. I want to open a new form at run time from the original form on a button click. And then close this new form (after 2,3 sec) programatically but from a thread other than gui main thread.
Can anybody guide me how to do it ?
Will the new form affect or hinder the things going on in the original main form ? (if yes than how to stop it ?)
To open from with button click please add the following code in the button event handler
var m = new Form1();
m.Show();
Here Form1 is the name of the form which you want to open.
Also to close the current form, you may use
this.close();
I would do it like this:
var form2 = new Form2();
form2.Show();
and to close current form I would use
this.Hide(); instead of
this.close();
check out this Youtube channel link for easy start-up tutorials you might find it helpful if u are a beginner
This is an old question, but answering for gathering knowledge.
We have an original form with a button to show the new form.
The code for the button click is below
private void button1_Click(object sender, EventArgs e)
{
New_Form new_Form = new New_Form();
new_Form.Show();
}
Now when click is made, New Form is shown. Since, you want to hide after 2 seconds we are adding a onload event to the new form designer
this.Load += new System.EventHandler(this.OnPageLoad);
This OnPageLoad function runs when that form is loaded
In NewForm.cs ,
public partial class New_Form : Form
{
private Timer formClosingTimer;
private void OnPageLoad(object sender, EventArgs e)
{
formClosingTimer = new Timer(); // Creating a new timer
formClosingTimer.Tick += new EventHandler(CloseForm); // Defining tick event to invoke after a time period
formClosingTimer.Interval = 2000; // Time Interval in miliseconds
formClosingTimer.Start(); // Starting a timer
}
private void CloseForm(object sender, EventArgs e)
{
formClosingTimer.Stop(); // Stoping timer. If we dont stop, function will be triggered in regular intervals
this.Close(); // Closing the current form
}
}
In this new form , a timer is used to invoke a method which closes that form.
Here is the new form which automatically closes after 2 seconds, we will be able operate on both the forms where no interference between those two forms.
For your knowledge,
form.close() will free the memory and we can never interact with that form again
form.hide() will just hide the form, where the code part can still run
For more details about timer refer this link, https://learn.microsoft.com/en-us/dotnet/api/system.timers.timer?view=netframework-4.7.2
You just need to use Dispatcher to perform graphical operation from a thread other then UI thread. I don't think that this will affect behavior of the main form. This may help you :
Accessing UI Control from BackgroundWorker Thread
This might also help:
void ButtQuitClick(object sender, EventArgs e)
{
QuitWin form = new QuitWin();
form.Show();
}
Change ButtQuit to your button name and also change QuitWin to the name of the form that you made.
When the button is clicked it will open another window, you will need to make another form and a button on your main form for it to work.
private void btnchangerate_Click(object sender, EventArgs e)
{
this.Hide(); //current form will hide
Form1 fm = new Form1(); //another form will open
fm.Show();
}
on click btn current form will hide and new form will open

how to make program that be in the taskbar windows-CE

how to make C# program that will be All time in the taskbar ?
i want to Build a Keyboard program.
i need that when i open the device the program will open and be in the taskbar.
another question is, when i have an external program that has a Textbox, how
to make that when i press any key in my C# keyboard it will be in this external Textbox ?
thank's in advance
It's not implemented in the CF, but the NotifyIcon class is what you're after. The SDF does implement it. It would be used something like this:
m_notifyIcon = new NotifyIcon();
m_notifyIcon.Icon = this.Icon;
m_notifyIcon.Visible = true;
m_notifyIcon.Click += new EventHandler(m_notifyIcon_Click);
m_notifyIcon.DoubleClick += new EventHandler(m_notifyIcon_DoubleClick);
EDIT
If you want to implement this yourself, the place to start is with the Shell_NotifyIcon API. You'll want to pass it the handle to a MessageWindow class and handle the WM_NOTIFY messages.
To Create a system Tray application in Windows-CE, put some code like:
CSystemTray m_TrayIcon; // Member variable of some class
...
// in some member function maybe...
m_TrayIcon.Create(pParentWnd, WM_MY_NOTIFY, "Click here",
hIcon, nTrayIconID);
Eg. For a non-MFC tray icon, do the following:
Collapse
CSystemTray m_TrayIcon; // Member variable of some class
...
// in some member function maybe...
m_TrayIcon.Create(hInstance, NULL, WM_MY_NOTIFY,
"Click here", hIcon, nID);
// Send all menu messages to hMyMainWindow
m_TrayIcon.SetTargetWnd(hMyMainWindow);
As found here:
http://www.codeproject.com/KB/shell/systemtray.aspx
To create a system tray application in Windows XP or Windows 7/Vista, put some code like this in your project:
private void Form1_Resize(object sender, System.EventArgs e)
{
if (FormWindowState.Minimized == WindowState)
Hide();
}
and this to handle the system tray click
private void notifyIcon1_DoubleClick(object sender,
System.EventArgs e)
{
Show();
WindowState = FormWindowState.Normal;
}
This and more information found at :
http://www.developer.com/net/net/article.php/3336751/C-Tip-Placing-Your-C-Application-in-the-System-Tray.htm

Single Form Hide on Startup

I have an application with one form in it, and on the Load method I need to hide the form.
The form will display itself when it has a need to (think along the lines of a outlook 2003 style popup), but I can' figure out how to hide the form on load without something messy.
Any suggestions?
I'm coming at this from C#, but should be very similar in vb.net.
In your main program file, in the Main method, you will have something like:
Application.Run(new MainForm());
This creates a new main form and limits the lifetime of the application to the lifetime of the main form.
However, if you remove the parameter to Application.Run(), then the application will be started with no form shown and you will be free to show and hide forms as much as you like.
Rather than hiding the form in the Load method, initialize the form before calling Application.Run(). I'm assuming the form will have a NotifyIcon on it to display an icon in the task bar - this can be displayed even if the form itself is not yet visible. Calling Form.Show() or Form.Hide() from handlers of NotifyIcon events will show and hide the form respectively.
Usually you would only be doing this when you are using a tray icon or some other method to display the form later, but it will work nicely even if you never display your main form.
Create a bool in your Form class that is defaulted to false:
private bool allowshowdisplay = false;
Then override the SetVisibleCore method
protected override void SetVisibleCore(bool value)
{
base.SetVisibleCore(allowshowdisplay ? value : allowshowdisplay);
}
Because Application.Run() sets the forms .Visible = true after it loads the form this will intercept that and set it to false. In the above case, it will always set it to false until you enable it by setting allowshowdisplay to true.
Now that will keep the form from displaying on startup, now you need to re-enable the SetVisibleCore to function properly by setting the allowshowdisplay = true. You will want to do this on whatever user interface function that displays the form. In my example it is the left click event in my notiyicon object:
private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Left)
{
this.allowshowdisplay = true;
this.Visible = !this.Visible;
}
}
I use this:
private void MainForm_Load(object sender, EventArgs e)
{
if (Settings.Instance.HideAtStartup)
{
BeginInvoke(new MethodInvoker(delegate
{
Hide();
}));
}
}
Obviously you have to change the if condition with yours.
protected override void OnLoad(EventArgs e)
{
Visible = false; // Hide form window.
ShowInTaskbar = false; // Remove from taskbar.
Opacity = 0;
base.OnLoad(e);
}
At form construction time (Designer, program Main, or Form constructor, depending on your goals),
this.WindowState = FormWindowState.Minimized;
this.ShowInTaskbar = false;
When you need to show the form, presumably on event from your NotifyIcon, reverse as necessary,
if (!this.ShowInTaskbar)
this.ShowInTaskbar = true;
if (this.WindowState == FormWindowState.Minimized)
this.WindowState = FormWindowState.Normal;
Successive show/hide events can more simply use the Form's Visible property or Show/Hide methods.
Try to hide the app from the task bar as well.
To do that please use this code.
protected override void OnLoad(EventArgs e)
{
Visible = false; // Hide form window.
ShowInTaskbar = false; // Remove from taskbar.
Opacity = 0;
base.OnLoad(e);
}
Thanks.
Ruhul
Extend your main form with this one:
using System.Windows.Forms;
namespace HideWindows
{
public class HideForm : Form
{
public HideForm()
{
Opacity = 0;
ShowInTaskbar = false;
}
public new void Show()
{
Opacity = 100;
ShowInTaskbar = true;
Show(this);
}
}
}
For example:
namespace HideWindows
{
public partial class Form1 : HideForm
{
public Form1()
{
InitializeComponent();
}
}
}
More info in this article (spanish):
http://codelogik.net/2008/12/30/primer-form-oculto/
I have struggled with this issue a lot and the solution is much simpler than i though.
I first tried all the suggestions here but then i was not satisfied with the result and investigated it a little more.
I found that if I add the:
this.visible=false;
/* to the InitializeComponent() code just before the */
this.Load += new System.EventHandler(this.DebugOnOff_Load);
It is working just fine.
but I wanted a more simple solution and it turn out that if you add the:
this.visible=false;
/* to the start of the load event, you get a
simple perfect working solution :) */
private void
DebugOnOff_Load(object sender, EventArgs e)
{
this.Visible = false;
}
You're going to want to set the window state to minimized, and show in taskbar to false. Then at the end of your forms Load set window state to maximized and show in taskbar to true
public frmMain()
{
Program.MainForm = this;
InitializeComponent();
this.WindowState = FormWindowState.Minimized;
this.ShowInTaskbar = false;
}
private void frmMain_Load(object sender, EventArgs e)
{
//Do heavy things here
//At the end do this
this.WindowState = FormWindowState.Maximized;
this.ShowInTaskbar = true;
}
Put this in your Program.cs:
FormName FormName = new FormName ();
FormName.ShowInTaskbar = false;
FormName.Opacity = 0;
FormName.Show();
FormName.Hide();
Use this when you want to display the form:
var principalForm = Application.OpenForms.OfType<FormName>().Single();
principalForm.ShowInTaskbar = true;
principalForm.Opacity = 100;
principalForm.Show();
This works perfectly for me:
[STAThread]
static void Main()
{
try
{
frmBase frm = new frmBase();
Application.Run();
}
When I launch the project, everything was hidden including in the taskbar unless I need to show it..
Override OnVisibleChanged in Form
protected override void OnVisibleChanged(EventArgs e)
{
this.Visible = false;
base.OnVisibleChanged(e);
}
You can add trigger if you may need to show it at some point
public partial class MainForm : Form
{
public bool hideForm = true;
...
public MainForm (bool hideForm)
{
this.hideForm = hideForm;
InitializeComponent();
}
...
protected override void OnVisibleChanged(EventArgs e)
{
if (this.hideForm)
this.Visible = false;
base.OnVisibleChanged(e);
}
...
}
Launching an app without a form means you're going to have to manage the application startup/shutdown yourself.
Starting the form off invisible is a better option.
This example supports total invisibility as well as only NotifyIcon in the System tray and no clicks and much more.
More here: http://code.msdn.microsoft.com/TheNotifyIconExample
As a complement to Groky's response (which is actually the best response by far in my perspective) we could also mention the ApplicationContext class, which allows also (as it's shown in the article's sample) the ability to open two (or even more) Forms on application startup, and control the application lifetime with all of them.
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
MainUIForm mainUiForm = new MainUIForm();
mainUiForm.Visible = false;
Application.Run();
}
I had an issue similar to the poster's where the code to hide the form in the form_Load event was firing before the form was completely done loading, making the Hide() method fail (not crashing, just wasn't working as expected).
The other answers are great and work but I've found that in general, the form_Load event often has such issues and what you want to put in there can easily go in the constructor or the form_Shown event.
Anyways, when I moved that same code that checks some things then hides the form when its not needed (a login form when single sign on fails), its worked as expected.
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Form1 form1 = new Form1();
form1.Visible = false;
Application.Run();
}
private void ExitToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
Application.Exit();
}
Here is a simple approach:
It's in C# (I don't have VB compiler at the moment)
public Form1()
{
InitializeComponent();
Hide(); // Also Visible = false can be used
}
private void Form1_Load(object sender, EventArgs e)
{
Thread.Sleep(10000);
Show(); // Or visible = true;
}
In the designer, set the form's Visible property to false. Then avoid calling Show() until you need it.
A better paradigm is to not create an instance of the form until you need it.
Based on various suggestions, all I had to do was this:
To hide the form:
Me.Opacity = 0
Me.ShowInTaskbar = false
To show the form:
Me.Opacity = 100
Me.ShowInTaskbar = true
Why do it like that at all?
Why not just start like a console app and show the form when necessary? There's nothing but a few references separating a console app from a forms app.
No need in being greedy and taking the memory needed for the form when you may not even need it.
I do it like this - from my point of view the easiest way:
set the form's 'StartPosition' to 'Manual', and add this to the form's designer:
Private Sub InitializeComponent()
.
.
.
Me.Location=New Point(-2000,-2000)
.
.
.
End Sub
Make sure that the location is set to something beyond or below the screen's dimensions. Later, when you want to show the form, set the Location to something within the screen's dimensions.

Categories

Resources