C# Run application MINIMIZED at windows startup - c#

I got the following code to run the application at windows startup:
private void SetStartup(string AppName, bool enable)
{
string runKey = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run";
Microsoft.Win32.RegistryKey startupKey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(runKey);
if (enable)
{
if (startupKey.GetValue(AppName) == null)
{
startupKey.Close();
startupKey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(runKey, true);
startupKey.SetValue(AppName, Application.ExecutablePath.ToString());
startupKey.Close();
}
}
else
{
startupKey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(runKey, true);
startupKey.DeleteValue(AppName, false);
startupKey.Close();
}
}
It works. but I want the program to start minimized (at windows startup only).
I didnt find a working code / good explanation how to do it.
Can you help me please?
thanks.

Have you tried
this.WindowState = FormWindowState.Minimized;
If you want to start minimized at windows startup only you can add extra argument to command line, like myapp.exe --start-minimized, then you can parse this parameter and detect whether you need to start minimized or not.

Since this is only adding a registry key to SOFTWARE\Microsoft\Windows\CurrentVersion\Run which causes the OS to start the app at startup there isn't a lot you can do unless the application you want to startup accepts a command line parameter to start minimized (You could then add the parameter to the executable path of the key).
If this is a necessary function and you can't modify the program to accept a parameter to minimize the only thing I can think of doing would be to write a program that would minimize these apps after the OS has started them.

Don't normally revive old threads but one Easy way including minimize to system tray, for WPF like this:
public class EntryPoint
{
[STAThread]
public static void Main(string[] args)
{
SingleInstanceManager manager = new SingleInstanceManager();
manager.Run(args);
}
}
public class SingleInstanceManager : WindowsFormsApplicationBase
{
SingleInstanceApplication app;
public SingleInstanceManager()
{
this.IsSingleInstance = true;
}
protected override bool OnStartup(Microsoft.VisualBasic.ApplicationServices.StartupEventArgs e)
{
app = new SingleInstanceApplication();
app.Run();
return false;
}
protected override void OnStartupNextInstance(StartupNextInstanceEventArgs eventArgs)
{
base.OnStartupNextInstance(eventArgs);
app.Activate();
}
}
public class SingleInstanceApplication : Application
{
protected override void OnStartup(System.Windows.StartupEventArgs e)
{
base.OnStartup(e);
bool startMinimized = false;
for (int i = 0; i != e.Args.Length; ++i)
{
if (e.Args[i] == "/StartMinimized")
{
startMinimized = true;
}
}
MainWindow mainWindow = new MainWindow();
if (startMinimized)
{
mainWindow.WindowState = WindowState.Minimized;
}
mainWindow.Show();
}
public void Activate()
{
this.MainWindow.Activate();
this.MainWindow.WindowState = WindowState.Normal;
}
}
}
Your Window class:
public partial class MainWindow : Window
{
private Window _window;
public MainWindow()
{
InitializeComponent();
SetStartup("AppName", true);
}
private void SetStartup(string AppName, bool enable)
{
string runKey = #"SOFTWARE\Microsoft\Windows\CurrentVersion\Run";
Microsoft.Win32.RegistryKey startupKey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(runKey);
if (enable)
{
if (startupKey.GetValue(AppName) == null)
{
startupKey.Close();
startupKey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(runKey, true);
startupKey.SetValue(AppName, Assembly.GetExecutingAssembly().Location + " /StartMinimized");
startupKey.Close();
}
}
else
{
startupKey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(runKey, true);
startupKey.DeleteValue(AppName, false);
startupKey.Close();
}
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
if (this.WindowState == System.Windows.WindowState.Minimized)
{
var minimized = (_window.WindowState == WindowState.Minimized);
_window.ShowInTaskbar = !minimized;
}
else
ShowInTaskbar = true;
}
Worked first time so had to post. I'm using WPF notifyicon, hence why i needed it to go to system tray on windows startup.

Had a really hard time finding a good answer to this, finally found it in a really old book. On my Forms application, just opened the program.cs and changed
Application.Run(new Form1());
to
Form1 f = new Form1();
f.WindowState = FormWindowState.Minimized;
f.ShowInTaskbar = false;
Application.Run(f);
and it opens without a flicker directly to the tray. This app was more just a service, so set it to just have a notify icon and exit button when right clicked. Hope this helps!!

I have strugled with the same issue, and found a working solution:
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();
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();
}
}

Related

Opening next file with the same instance of my app

I associated .pdf files with my C#.NET WPF app in Windows.
If I open the pdf file by clicking on it, array "param" is:
string[] param = Environment.GetCommandLineArgs();
Which contains two paths:
1) Path to my app (param[0])
2) Path to opened (param[1])
I have set in the C# code (app.xaml.cs) that only one instance of my app may be opened in Windows. If I try to open a second instance, the main window of the first instance is activated.
But now, if I open the next pdf file by click on it “param” contains the path to the first file logically, therefore I can not open the next file :0(.
How should I solve this problem? I don’t want to move to the next instance of the app!
Here is my app.xaml.code
public partial class App : Application
{
App()
{
InitializeComponent();
}
[STAThread]
static void Main()
{
SingleInstanceManager manager = new SingleInstanceManager();
manager.Run(new[] { "test" });
}
}
public class SingleInstanceManager : WindowsFormsApplicationBase
{
SingleInstanceApplication app;
public SingleInstanceManager()
{
this.IsSingleInstance = true;
}
protected override bool OnStartup(Microsoft.VisualBasic.ApplicationServices.StartupEventArgs e)
{
// First time app is launched
app = new SingleInstanceApplication();
app.Run();
return false;
}
protected override void OnStartupNextInstance(StartupNextInstanceEventArgs eventArgs)
{
// Subsequent launches
base.OnStartupNextInstance(eventArgs);
app.Activate();
}
}
public class SingleInstanceApplication : Application
{
protected override void OnStartup(System.Windows.StartupEventArgs e)
{
base.OnStartup(e);
// Create and show the application's main window
MainWindow window = new MainWindow();
window.Show();
}
public void Activate()
{
// Reactivate application's main window
this.MainWindow.WindowState = WindowState.Normal;
this.MainWindow.Activate();
((MainWindow)this.MainWindow).SpracujStartovacieParametre();
}
}
Here is my solution:
public partial class App : Application
{
App()
{
InitializeComponent();
}
[STAThread]
static void Main()
{
SingleInstanceManager manager = new SingleInstanceManager();
//manager.Run(new[] { "test" });
manager.Run(Environment.GetCommandLineArgs());
}
}
public class SingleInstanceManager : WindowsFormsApplicationBase
{
SingleInstanceApplication app;
public SingleInstanceManager()
{
this.IsSingleInstance = true;
}
protected override bool OnStartup(Microsoft.VisualBasic.ApplicationServices.StartupEventArgs e)
{
// First time app is launched
app = new SingleInstanceApplication();
app.Run();
return false;
}
protected override void OnStartupNextInstance(StartupNextInstanceEventArgs eventArgs)
{
// Subsequent launches
base.OnStartupNextInstance(eventArgs);
//MessageBox.Show("Event arguments:"+ eventArgs.ToString());
app.Activate(eventArgs.CommandLine.ToArray<string>());
}
}
public class SingleInstanceApplication : Application
{
protected override void OnStartup(System.Windows.StartupEventArgs e)
{
base.OnStartup(e);
// Create and show the application's main window
MainWindow window = new MainWindow();
window.Show();
}
public void Activate(string[] eventArgs)
{
((MainWindow)this.MainWindow).SpracujCommandLineArgs(eventArgs);
this.MainWindow.WindowState = WindowState.Maximized;
this.MainWindow.Activate();
}
}

GeckoFx after using Xpcom.Shutdown(), Xpcom.Initialize(path) can not be used any more

I would like to have more then one gecko browser in my C# app.
So what I did:
FORM UI code:
public partial class GeckoBrowserForm : Form
{
static GeckoBrowserForm()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
}
public GeckoBrowserForm(string xulRunnerPath, string url)
{
InitializeXulRunner(xulRunnerPath);
m_Url = url;
FormBorderStyle = FormBorderStyle.FixedToolWindow;
ShowInTaskbar = false;
StartPosition = FormStartPosition.Manual;
Location = new Point(0, 0);
Size = new Size(800, 800);
Done = false;
InitializeComponent();
}
private static void InitializeXulRunner(string path)
{
if (!Xpcom.IsInitialized)
{
Xpcom.Initialize(path);
}
}
protected override void OnLoad(EventArgs e)
{
m_GeckoWebBrowser.Parent = this;
m_GeckoWebBrowser.Dock = DockStyle.Fill;
m_GeckoWebBrowser.DocumentCompleted += (s, ee) =>
{
var geckoDomElement = m_GeckoWebBrowser.Document.DocumentElement;
if (geckoDomElement is GeckoHtmlElement)
{
GeckoHtmlElement element = (GeckoHtmlElement)geckoDomElement;
DocumentDomHtml = element.InnerHtml;
}
if (m_Url.Equals(m_GeckoWebBrowser.Document.Url.ToString(), StringComparison.OrdinalIgnoreCase))
{
Done = true;
}
};
m_GeckoWebBrowser.Navigate(m_Url);
}
and in worker thread, not UI:
if (Xpcom.IsInitialized)
{
Xpcom.Shutdown();
}
using (GeckoBrowserForm geckoBrowserForm = new GeckoBrowserForm(XulRunnerPath, propertyBag.ResponseUri.ToString()))
{
geckoBrowserForm.Show();
while (!geckoBrowserForm.Done)
{
Application.DoEvents();
}
string html = geckoBrowserForm.DocumentDomHtml;
if (!string.IsNullOrEmpty(html))
{
propertyBag.GetResponse = () => new MemoryStream(Encoding.UTF8.GetBytes(html));
}
base.Process(crawler, propertyBag);
}
problemis that after I use Xpcom.Shutdown(); I can not use Xpcom.Initialize(path); any more. Program just stopped without any error.
Why?
I know what geckoFx can be only used in the same UI thread that way I want to initialite it again
public static void AssertCorrectThread()
{
if (Thread.CurrentThread.ManagedThreadId != _XpcomThreadId)
{
throw new InvalidOperationException("GeckoFx can only be called from the same thread on which it was initialized (normally the UI thread).");
}
}
It appears that this is still a problem, which matters a great deal when unit testing. Run all unit tests (which start with an initialize), and everything is fine. Attempt to run them again, and you potentially run into issues, depending on the state of xpCom, because there's no way to shutdown.
similar issue here: Using GeckoFX in a multithreaded application

Splash Screen in WPF two monitors

I am developing a WPF application. I am using two monitors. I am using splash screen to pop up on window when some function is executing.
The problem I have is when I move the application to secondary monitor and start processing functions splash screen is still being displayed in primary monitor instead on secondary monitor.
Any help on this?
you can try for BusyIndicator if suitable for you or else you can try below code to show Splash Window.
void TemplateSelector_Loaded(object sender, RoutedEventArgs e)
{
showWin();
Thread.Sleep(10000);
CloseWin();
}
private void CloseWin()
{
WindowManager.Close();
}
Window tempWindow = new Window();
public void showWin()
{
WindowManager.LaunchWindowNewThread<SplashWindow>();
}
}
public class WindowManager
{
private static Window win;
public static void LaunchWindowNewThread<T>() where T : Window, new()
{
Thread newWindowThread = new Thread(ThreadStartingPoint);
newWindowThread.SetApartmentState(ApartmentState.STA);
newWindowThread.IsBackground = true;
Func<Window> f = delegate
{
T win = new T();
return win;
};
newWindowThread.Start(f);
}
private static void ThreadStartingPoint(object t)
{
Func<Window> f = (Func<Window>)t;
win = f();
win.WindowStartupLocation = WindowStartupLocation.CenterScreen;
win.Topmost = true;
win.Show();
Dispatcher.Run();
}
public static void Close()
{
if (win != null)
win.Dispatcher.BeginInvokeShutdown(DispatcherPriority.Send);
}
}

C# Sql Server "loading window"

This is my first post here, but I've using this site regularly to help me with my own app's, and I should say that this site has been a great help to me, so thanks to everyone.
Now my question:
I'm developing my first software app that exchanges data between a sql server and the app itself. It's beeing developed in C#. Saving or retreiving data from the sql server database is no problem.
What I want is a way to inform the user of the delay between the local machine (where the app is installed) and the server. I can make some animations or simply display some text messages. What I need help with is how to create the code that activates/fires/runs when that server communication time is running.
If you can't understand the idea, picture a video game. When it's loading (in some games) you can see the loading screen before the game starts. I need some code that displays that "loading window" when the the app is downloading or uploading data from/to the server.
I would appreciate any code example or web site recommendation.
PS: Sorry for the extensive text, but I want to make sure everyone understand so I don't have to repeat it again :P
How do I implement a progress bar in C#?
How to create a smooth progress bar in Visual C#
ProgressBar Class
I have developed a simple PleaseWait class 2 years ago, but I didn't update this class, It works very well, have look hope this will give you an idea to implement your logic.
public partial class frmWait : Form
{
public frmWait()
{
InitializeComponent();
}
bool _isMoving = false;
int _moveStart_x = 0;
int _moveStart_y = 0;
private void tmrProgress_Tick(object sender, EventArgs e)
{
if (barProgress.Value == barProgress.Maximum)
barProgress.Value = barProgress.Minimum;
else
barProgress.Value += 1;
}
private void btnCancel_Click(object sender, EventArgs e)
{
Close();
PleaseWait.Abort();
}
protected override CreateParams CreateParams
{
get
{
System.Windows.Forms.CreateParams p = base.CreateParams;
p.ClassStyle += 0x20000;
p.ExStyle += 0x8000000;
return p;
}
}
protected override void WndProc(ref Message m)
{
const int WM_NCHITTEST = 132;
base.WndProc(ref m);
switch (m.Msg)
{
case WM_NCHITTEST:
if (m.Result.ToInt32() == 1)
m.Result = new IntPtr(2);
break;
}
}
private void panelEx1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
_isMoving = true;
_moveStart_x = e.X;
_moveStart_y = e.Y;
}
}
private void panelEx1_MouseUp(object sender, MouseEventArgs e)
{
_isMoving = false;
}
private void pnlContainer_MouseMove(object sender, MouseEventArgs e)
{
if (_isMoving)
this.Location = new Point(Location.X + e.X - _moveStart_x, Location.Y + e.Y - _moveStart_y);
}
}
public class PleaseWait
{
#region Static Operations
private static Boolean _isAborted = false;
private static Boolean _isVisible = false;
private static frmWait _waitForm;
private static String _waitingState = "";
private static Boolean _autoClose = false;
private static Boolean _cancelable = false;
private static System.Threading.Thread _waiterThred;
public delegate void CancelButtonPressed();
public static event CancelButtonPressed OnCancel;
public static Boolean AutoClose
{
get { return PleaseWait._autoClose; }
set { PleaseWait._autoClose = value; }
}
public static string WaitingState
{
get { return PleaseWait._waitingState; }
set { PleaseWait._waitingState = value; }
}
public static bool IsVisible
{
get { return _isVisible; }
internal set { _isVisible = value; }
}
public static void ShowPleaseWait()
{
ShowPleaseWait("", _autoClose, false);
}
public static void ShowPleaseWait(string waitingState)
{
ShowPleaseWait(waitingState, _autoClose, false);
}
public static void ShowPleaseWait(bool autoClose)
{
ShowPleaseWait("", autoClose, false);
}
public static void ShowPleaseWait(string waitingState, bool autoClose, bool cancelable)
{
if (_waiterThred != null)
{
if (_isVisible)
{
// the please wait it woking, just continue and apply the changes
_waitingState = waitingState;
_autoClose = autoClose;
_cancelable = cancelable;
return;
}
else
{
_waiterThred.Abort();
_waiterThred = null;
}
}
_waitingState = waitingState;
_autoClose = autoClose;
_cancelable = cancelable;
_isAborted = false;
_isVisible = false;
if (_autoClose)
Application.Idle += new EventHandler(Application_Idle);
_waiterThred = new System.Threading.Thread(DisplayWaitingForm);
_waiterThred.IsBackground = true;
_waiterThred.Name = "Please Wait....";
_waiterThred.Start();
Application.DoEvents();
}
public static void Abort()
{
_isAborted = true;
}
private static void Application_Idle(object sender, EventArgs e)
{
if (_autoClose)
_isAborted = true;
}
private static void DisplayWaitingForm()
{
if (_waitForm != null)
{
if (!_waitForm.IsDisposed)
_waitForm.Dispose();
_waitForm = null;
_isVisible = false;
}
try
{
if (_isAborted)
return;
_waitForm = new frmWait();
if (_cancelable)
{
_waitForm.btnCancel.Enabled = true;
_waitForm.btnCancel.Click += new EventHandler(btnCancel_Click);
}
try
{
_isVisible = true;
_waitForm.Show();
_waitForm.Focus();
while (!_isAborted)
{
System.Threading.Thread.Sleep(15);
_waitForm.lblMessage.Text = _waitingState;
Application.DoEvents();
_waitForm.lblMessage.Text = _waitingState;
}
_isVisible = false;
}
finally
{
FreeWaitingForm();
}
}
finally
{
_isVisible = false;
}
}
static void btnCancel_Click(object sender, EventArgs e)
{
if (_waitForm.InvokeRequired)
{
_waitForm.BeginInvoke(new EventHandler(btnCancel_Click), new object[] { e });
}
else
{
if (OnCancel != null)
OnCancel.Invoke();
}
}
private static void FreeWaitingForm()
{
_waitingState = "";
_isVisible = false;
if (_waitForm == null)
{
return;
}
_waitForm.Hide();
if (!_waitForm.IsDisposed)
_waitForm.Dispose();
_waitForm = null;
}
#endregion
}
use like following code :
PleaseWait.ShowPleaseWait("Please wait", true, false);
// If second param is true then it will close the form automatically.
// If third param is true the it will expose a cancel button, so you can cancel your Asynchronous operations.
I didn't insert design code, you can understand by looking at code.
hope this help.
First let me thank you for your replies.
Toby your answer got me thinking about thread monitoring my sql connections but it was a bit tricky and confusing since the app is still in develop and will use a lot more connections.
S.Amani answer it wasn't quite what I want, but thanks to that I found a easier way. I created a form (could be anything else), placed a label saying: Saving To Data Base, took out the top bar, defined location and defined it's parent to be disabled when shown and enabled when closed. The following code is what I put inside my DataBaseInteractionClass
private Wait myCustomWaitDialog = new Wait(); // My Waiting form
private void SaveToDatabase(myObjectToSave obj) // Method called to save data do DB
{
// Create the connections and queries
(...)
// This is what I did
// Show Waiting Form
myCustomWaitDialog.Show();
// Instanciate the command that will carry the query and to DB
SqlCommand command = new SqlCommand(Queries.GetData(code), conn);
// This is important
//Create event that will fire when the command completes
command.StatementCompleted += new StatementCompletedEventHandler(command_StatementCompleted);
// Execute the transaction
SqlDataReader reader = command.ExecuteReader();
// Rest of the code (validations, close connections, try/catch, etc
(...)
}
void command_StatementCompleted(object sender, StatementCompletedEventArgs e)
{
// This is the method that closes my Waiting Dialog
myCustomWaitDialog.CloseDialog();
myCustomWaitDialog.Dispose();
}
It's not quite what I want yet, but is the best solution that I found so far. For now it will do :)
Anyway, thanks for the replies and I hope this helps someone else.

Using Microsoft.VisualBasic.ApplicationServices to manage an application's single instance

I have managed to find the following code from StackOverflow:
using Microsoft.VisualBasic.ApplicationServices;
using System.Windows.Forms;
namespace ExciteEngine2.MainApplication {
public class SingleInstanceController: WindowsFormsApplicationBase {
public delegate Form CreateMainForm();
public delegate void StartNextInstanceDelegate(Form mainWindow);
private readonly CreateMainForm formCreation;
private readonly StartNextInstanceDelegate onStartNextInstance;
public SingleInstanceController() {
}
public SingleInstanceController(AuthenticationMode authenticationMode)
: base(authenticationMode) {
}
public SingleInstanceController(CreateMainForm formCreation, StartNextInstanceDelegate onStartNextInstance) {
// Set whether the application is single instance
this.formCreation = formCreation;
this.onStartNextInstance = onStartNextInstance;
IsSingleInstance = true;
StartupNextInstance += this_StartupNextInstance;
}
private void this_StartupNextInstance(object sender, StartupNextInstanceEventArgs e) {
if (onStartNextInstance != null) {
onStartNextInstance(MainForm);
// This code will be executed when the user tries to start the running program again,
// for example, by clicking on the exe file.
// This code can determine how to re-activate the existing main window of the running application.
}
}
protected override void OnCreateMainForm() {
// Instantiate your main application form
MainForm = formCreation();
}
//public void Run() {
// string[] commandLine = new string[0];
// base.Run(commandLine);
//}
protected override void OnRun() {
base.OnRun();
}
}
}
And I have this in my Program.cs:
private static Form CreateForm() {
return new AppMDIRibbon();
}
private static void OnStartNextInstance(Form mainWindow)
{
// When the user tries to restart the application again, the main window is activated again.
mainWindow.WindowState = FormWindowState.Maximized;
}
[STAThread]
static void Main(string[] args) {
SingleInstanceController ApplicationSingleInstanceController = new SingleInstanceController(CreateForm, OnStartNextInstance);
ApplicationSingleInstanceController.Run(args);
#region Application Logic
#endregion
}
Now, I have a lot of application logic that I need BEFORE the Run():
#region Application Logic
//Uninstall
foreach (string arg in args) {
if (arg.Split('=')[0] == "/u") {
ApplicationLogger.Info("Uninstallation command received.");
Process.Start(new ProcessStartInfo(Environment.GetFolderPath(Environment.SpecialFolder.System) + "\\msiexec.exe", "/x " + arg.Split('=')[1]));
return;
}
}
SetupXPO();
SetupLogging();
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB");
Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-GB");
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.ThreadException += Application_ThreadException;
try {
ApplicationLogger.Info("Setting Telerik Theme: " + ConfigurationManager.AppSettings["ThemeToUse"]);
ThemeResolutionService.ApplicationThemeName = ConfigurationManager.AppSettings["ThemeToUse"];
}
catch (Exception ex) {
ApplicationLogger.Error("Exception while setting Telerik Theme.", ex);
ThemeResolutionService.ApplicationThemeName = "ControlDefault";
}
DevExpress.UserSkins.OfficeSkins.Register();
DevExpress.UserSkins.BonusSkins.Register();
DevExpress.Skins.SkinManager.EnableFormSkins();
DevExpress.Skins.SkinManager.EnableMdiFormSkins();
if (args.Contains("/dx")) {
Application.Run(new AppMDIRibbonDX());
ApplicationLogger.Info("Application (DX) started.");
}
else {
Application.Run(new AppMDIRibbon());
ApplicationLogger.Info("Application started.");
}
#endregion
How can I setup this logic? I'm using a commandline argument to actually start an alternate form. I'm using a commandline argument to cause an uninstallation and also calling some method to setup DB and logging. Similarly, I'm setting up culture and themes too. All this before the actual application run. Can anyone suggest?
If you simplify the Visual Basic-derived class you linked, you can just replace your current call to Application.Run(). This does depend on how you want to handle subsequent instances.
With the version below, just change you calls of: Application.Run(myForm) to SingleInstanceApplication.Run(myForm);
public sealed class SingleInstanceApplication : WindowsFormsApplicationBase
{
private static SingleInstanceApplication _application;
private SingleInstanceApplication()
{
base.IsSingleInstance = true;
}
public static void Run(Form form)
{
_application = new SingleInstanceApplication {MainForm = form};
_application.StartupNextInstance += NextInstanceHandler;
_application.Run(Environment.GetCommandLineArgs());
}
static void NextInstanceHandler(object sender, StartupNextInstanceEventArgs e)
{
// Do whatever you want to do when the user launches subsequent instances
// like when the user tries to restart the application again, the main window is activated again.
_application.MainWindow.WindowState = FormWindowState.Maximized;
}
}
Then your Main() method contains your "Application Logic"
[STAThread]
static void Main(string[] args) {
#region Application Logic
//Uninstall
foreach (string arg in args) {
if (arg.Split('=')[0] == "/u") {
ApplicationLogger.Info("Uninstallation command received.");
Process.Start(new ProcessStartInfo(Environment.GetFolderPath(Environment.SpecialFolder.System) + "\\msiexec.exe", "/x " + arg.Split('=')[1]));
return;
}
}
SetupXPO();
SetupLogging();
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB");
Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-GB");
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.ThreadException += Application_ThreadException;
try {
ApplicationLogger.Info("Setting Telerik Theme: " + ConfigurationManager.AppSettings["ThemeToUse"]);
ThemeResolutionService.ApplicationThemeName = ConfigurationManager.AppSettings["ThemeToUse"];
}
catch (Exception ex) {
ApplicationLogger.Error("Exception while setting Telerik Theme.", ex);
ThemeResolutionService.ApplicationThemeName = "ControlDefault";
}
DevExpress.UserSkins.OfficeSkins.Register();
DevExpress.UserSkins.BonusSkins.Register();
DevExpress.Skins.SkinManager.EnableFormSkins();
DevExpress.Skins.SkinManager.EnableMdiFormSkins();
if (args.Contains("/dx")) {
SingleInstanceApplication.Run(new AppMDIRibbonDX());
ApplicationLogger.Info("Application (DX) started.");
}
else {
SingleInstanceApplication.Run(new AppMDIRibbon());
ApplicationLogger.Info("Application started.");
}
#endregion
}

Categories