Search

Sunday, March 16, 2008

How to Hide the Form and Run application in background in C# .NET

Want to Hide the Window Form Initially at program start up in C# using .NET Frame work? today i came across this situation and solved it!!! and Just thought of archiving my personal issues encountered during programming so that it might help or give some possible solutions to others

The tricky part here is that the second time you start the program, it needs to *not* run but communicate with the first instance of the program and tell it to make its window visible. You can do this with a technique shown in this MSDN magazine article. It uses the Visual Basic application framework, all the nasty details of having programs talk to each other are taken care of.

Start by adding a reference to Microsoft.VisualBasic.dll with Project + Add Reference. Then make your Program.cs source code file look like this:

using System;
using System.Windows.Forms;
using Microsoft.VisualBasic.ApplicationServices;

namespace WindowsApplication1 {
static class Program {
public static bool mShowEnabled;
[STAThread]
static void Main() {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
// NOTE: allow form to show when we're debugging the code!
if (System.Diagnostics.Debugger.IsAttached) mShowEnabled = true;
SingleInstanceProgram.Run(new Form1());
}
}
public class SingleInstanceProgram : WindowsFormsApplicationBase {
private SingleInstanceProgram() {
base.IsSingleInstance = true;
}
public static void Run(Form f) {
SingleInstanceProgram app = new SingleInstanceProgram();
app.MainForm = f;
app.StartupNextInstance += new StartupNextInstanceEventHandler(app.StartupHandler);
app.Run(Environment.GetCommandLineArgs());
}
private void StartupHandler(object sender, EventArgs e) {
// Second instance of program was started, allow main form to be visible
Program.mShowEnabled = true;
this.MainForm.Visible = true;
}
}
}

Open the source code for your main form and add this method:

protected override void SetVisibleCore(bool value) {
if (!Program.mShowEnabled) value = false;
base.SetVisibleCore(value);
}

Note that I added code to allow the form to be displayed when you are debugging it. Debugging would otherwise be pretty difficult.

0 comments:

Post a Comment

Other Interesting Articles



Related Article Widget by Yogith

Search Powered by Google