Bring main application form in front - c#

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
}
}

Related

Show MessageBox immediately in Windows Forms?

Is there any way to have a messagebox immediately pop up when a form opens? I just want to display a short message about how to use the form when it opens. I tried
private void myForm_Load(object sender, EventArgs e)
{
DialogResult dialogOpen = MessageBox.Show("Use the navigation menu to get started.", "Welcome!", MessageBoxButtons.OK);
}
but it doesn't work.
Showing a MessageBox during Form_Load works just fine for me. I literally copy/pasted the code from your original post, and it worked. I'm on .NET Framework 4.5 on Windows 8.1.
Are you sure your Load event handler is getting called? Perhaps the it's not hooked up to the Load event properly.
I don't see why it wouldn't work in Form_Load. Definitely try doing as others have pointed out by putting it beneath form initialization.
Though, given that you're just showing a message box, I don't think there is any reason to store the result, so a simple MessageBox.Show(message); Should do the trick.
As #s.m. said, from a UX point of view, having a notification thrown in your face as soon as the app starts would be very obnoxious, at least if you have it EVERY time. Personally, I would create a boolean Settings variable, set it to true the first time the message is displayed, and only display it when the setting is false, i.e. the first time the message is displayed.
private boolean splashShown = Properties.Settings.Default.splashShown;
private void Form_Load(object sender, EventArgs e)
{
if (!splashShown)
{
MessageBox.Show("message");
myForm.Properties.Settings.Default.splashShown = true;
myForm.Properties.Settings.Default.Save();
}
}
And set up the splashShown Setting in your form properties.
If the problem is that your Form_Load() method isn't actually attached to your Form.Load() event, you can double click the form window in the designer and it will automatically created the Form_Load() base method for you and attach it to the Form.Load() event
Is there a reason to use the Load method of the form? If not you could to it in the constructor of form. If you want it to show up immediately after your form loads, you should do it in the constructor after the form is initialized. It should look something like this:
public partial class myForm : Form
{
public myForm()
{
InitializeComponent();
DialogResult dialogOpen = MessageBox.Show("Use the navigation menu to get started.", "Welcome!", MessageBoxButtons.OK);
}
}
The constructor (public myForm()) and the InitializeComponent(); should be automatically added to the form by Visual Studio after creating it.
Form_Load event occurs before the form is really visible.
I use:
static private bool splashShown = false;
private void Form1_Activated(object sender, System.EventArgs e)
{
if (!splashShown)
{
MessageBox.Show("message");
splashShown = true;
}
}
I have used this and it works fine. App start brings up messagebox first before all else.
InitializeComponent();
MessageBox.Show("put your message here");

Access Form - instantiate it once

After closing a form, I can't access it anymore, because the object does not exist anymore.
Is there a way to avoid this kind of behaviour, without initiating the object everytime I perform an event?
This is the first Form called status, it's not the only one I need to create, that's why Iam asking.
This does not work: After closing the form and click on the menu item I get an reference error "Object does not exist", and therefor can't be accessed.
public partial class Main : Form
{
StatusForm statusForm = new StatusForm();
public Main()
{
InitializeComponent();
statusForm.MdiParent = this;
}
private void statusToolStripMenuItem_Click(object sender, EventArgs e)
{
statusForm.Show();
}
private void Main_Load(object sender, EventArgs e)
{
statusForm.Show();
}
}
If you use Close to close a form, it is unusable after that point. You have to create a new one.
However, if you want a persistent Form object, just call Form.Hide instead. This hides the form but leaves it "open".
MSDN notes this as well:
When the Close method is called on a Form displayed as a modeless
window, you cannot call the Show method to make the form visible,
because the form's resources have already been released. To hide a
form and then make it visible, use the Control.Hide method.

How to start the application directly in system tray? (.NET 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...

C# New form never gains focus

I have been trying to write a small app with its own option windows. When I try to launch the window I can never seem to set focus on the new form. This is not a mdi form, but merely a new form that I create when a user selects an option from the menu. It should be noted that Form.Show is return false, which means that the new form is never receiving focus.
I have tried multiple methods for loading the form and all have failed:
From Calling Form:
ServerForm SF = new ServerForm(ref DataLoader, false);
SF.Show();
SF.Focus();
// Fails
Inside the form itself:
this.Show();
this.BringToFront();
this.Activate();
this.TopMost = true;
// Fails
Setting Form to selectable:
this.SetStyle(System.Windows.Forms.ControlStyles.Selectable, true);
...
ServerForm SF = new ServerForm(ref DataLoader, false);
SF.Show();
SF.Focus();
// Fails
Using Old API:
[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern int ShowWindow(IntPtr handle, int nCmdShow);
ServerForm SF = new ServerForm(ref DataLoader, false);
ShowWindow(SF.Handle, 3);
SF.Show();
SF.Focus();
// Fails
Passing in Parent
ServerForm SF = new ServerForm(ref DataLoader, false);
SF.Show(this);
SF.Focus();
// Fails
In all of these cases the form will show up, but the form that spawned still will have focus over the new form. This happens even when I disable the old form before I create the new form.
Any suggestions?
It's because Form.canFocus() is false when the form loads. Use Form.Activate() on Form.Shown event. That's all.
private void ServerForm_Shown(object sender, EventArgs e)
{
this.Activate();
}
I solved with this (thanks to #Joel Coehoorn):
form.WindowState = FormWindowState.Minimized;
form.Shown += delegate(Object sender, EventArgs e) {
((Form)sender).WindowState = FormWindowState.Normal;
};
form.ShowDialog();
Set TopMost form property to true. Then
in program.cs:
var formLogin = new frmLogin();
formLogin.ShowDialog();
if (formLogin.DialogResult == DialogResult.Yes)
{
Application.Run(new frmMain());
}
in formLogin:
[DllImport("user32")]
public static extern int SetForegroundWindow(IntPtr hwnd);
...
private void frmLogin_Shown(object sender, EventArgs e)
{
SetForegroundWindow(this.Handle);
}
private void frmLogin_Deactivate(object sender, EventArgs e)
{
TopMost = false;
}
Remember that there is only a single user interface thread allowed in a winforms app.
Are you manipulating anything on the parent form after your call to Form.Show()? This
may cause the parent form to be focused again.
Remove everything you have used to try to focus, activate the form and rely just on the call to Form.Show(). This should be enough to load the form, and focus upon it. If anything, in your menu item handler. Comment out everything after your call to Show() and see if that works. Work backwards to see what caused your parent form to be refocused.
This seems to work. First I create the new form:
private void changeDefaultServerToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Enabled = false;
ServerForm SF = new ServerForm(ref DataLoader, true);
}
Then in the constructor for the new form I do the following:
this.BringToFront();
this.CenterToParent();
this.TopMost = true;
this.ShowDialog();
Apparently there is some sort of behind the scene difference between Form.Show and Form.ShowDialog. Not quites sure what it is, I can only think it has to do with setting the active parent somehow. Adding code after the call to construct the function does not seem to give back focus to the parent form. Which it shouldn't.
Have you tried setting the correct parent window in Form.Show()?
E.g.:
using(ServerForm SF = new ServerForm(ref DataLoader, false)) // if ServerForm is IDisposable
{
SF.Show(this);
}
Edit:
There's something going on that isn't in your question. Is your owning window a TopMost window?
Try to call ShowDialog(this). It helped in my case when I faced the same problem.

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