How to run code right when a C# application starts? - c#

I have put some code inside of the public MainWindow() {} but I kept getting some obscure XAML parsing errors as soon as I did that (not on my computer but on 3 others I've tried it on - yep!)
Is there the preferred way to run code AS SOON as t he application starts?
The theory is I want it to call home and ask it it's ok to start. If it's not, I want the app to close out. Call it a makeshift copy-protection :)

Under normal circumstances, WPF creates the Main method (the entrypoint of the application) for you. Your options
Create a handler for the Application.Startup event and put your code there. Alternatively, you can override the OnStartup() method.
If that's too late for you, put your code in the App's parameterless constructor (it probably doesn't exist, but you can create it).
If even that's too late, you can create your own Main() method. There are several ways how to do that. Probably the easiest is to put it in another class and tell Visual Studio you want to use this method in the project's properties.
On the other hand, you said you're getting some obscure XAML parsing errors. Maybe you should figure out what exactly do they mean?

You have Window.Loaded event in WPF.
But if if you want to check for run permission before application loads ( due some resource consuption or some business strategy) use a bootstrapper a separate small executable that first launched by mainexe and after if everything ok a bootstrapper runs main exe

Related

Is it possible to open winform form from dependency?

I have a visual studio windows forms application that has multiple projects, each having multiple forms. The project that loads on startup calls another project's form and closes its own. Referring to the startup program as "setup" and the other as "main". I have a scenario where I want to skip setup and be able to return to it later. Since setup is a dependency of main, and not the other way around, I cannot seem to create an instance of the setup form. Is this the case, or am I doing something wrong?
The call from setup to open main is as so
this.Hide();
frmDemo demo = new frmDemo();
demo.ShowDialog();
this.Close();
I want to do the same thing from main to setup form, but I am having trouble.
Essentially it should just be
frmSetup setup = new frmSetup();
setup.show();
But this isn't working because it cannot find the form.
Well if you want to reference Setup from Main then you need to add a reference in Main.
The problem then is that you will create a circular dependency, which is bad design (and I think you will also get compiler errors).
There are some ways to get around this, but the best approach it to make your Main program the first one that starts-up (not setup). Then during startup it launches the set-up form and waits until it is finished and then continues. And then when it needs to launch setup again, then it is no problem.
So you are effectively reversing the dependency.

Is Application.Restart bad?

I've got a .Net windows form application where a lot of variables are initialized in the Main_Load event and I have a situation where I want my DB re-queried and all vars set to null and re-initialized (basically the form 100% reloaded from the start), but I wrote my Main-Load in such a way (my fault) that it's not that easy to do...
I know I could get exactly what I want by simply calling Application.Restart and it does the trick beautifully, but I'm not sure if this is good programming practice or considered really bad.
Are there any problems that I'm likely to run into by using Application.Restart in this context?
Not friendly to debug, but there's nothing really wrong with it. It is the exact same as terminating the app and starting it again.
You can avoid it by simply creating a new instance of your main form and closing the old one. That however does require you to prevent the program from exiting. Code is here.
It's not that the method doesn't work; rather, many times programmers forget that they've put something in their code that would stop the application from automatically shutting down, or starting up.
Please follow this Thread
You can also do the job with
System.Diagnostics.Process.Start(Application.ExecutablePath);
Application.Exit();
To directly answer the question in the title, yes restarting an application to re-initialize variables is bad practice.
There are cases where restarting an application is usefull (in example self-update), but restarting to mimic a ReInitialize() method is bad in my opinion.
I had problems with this.
I really needed to restart a large Winforms Application, when a user logs off, to ensure all cached (my) data are purged.
Solved my problem by adding the Application.restart() into the Application Shutdown Event.
This works inside the VS environment and when running the EXE
If you want to find that event select your main project properties and from the Application (Side Tab) select View Application Events at the bottom.
My guess is that this works because it is very late on in the closing process. Hope this helps someone and, more importantly, it continues to work.

Intercepting and hiding a window before it appears

I am developing a (in-process) plug-in to application and as part of my plug-in I want to replace the application's tool-tips with my own. However, there is no API available for me to do so, so I've decided to go low-level.
I know the window class of the tool tip, but the question is, how do I detect it being created and how do I close it afterward?
Here's what I thought to do so far:
Create a system-wide hook on WM_CREATE
When caught, check the class and the process of the WM_CREATE target
Verify it is indeed the window I care about:
If the process is the one my plug-in is sitting in
And if the class is of the correct type
And if the correct application is in focus (in case of multiple applications)
Send a WM_DESTROY to the created window and create my own window at its position instead
How does it sound? Assuming there is indeed no API to handle the tooltips, is there a simpler way for what I need?
Thanks!
P.S Tagged as C++/C# as I intend to write it in these 2 languages (C++ for system-wide hook, C# for everything else)
If you know the type of the window you want to block, you can simply subclass it and handle the destruction in your own WndProc. Use GetClassLongPtr() with GCL_WNDPROC on the tooltip class, use SetClassLongPtr() with GCL_WNDPROC to set your own WndProc and have it call DestroyWindow() on WM_CREATE and call the old WndProc for the rest..
This won't work. Consider the view of the application that you're replacing the tooltips of and assuming that you could tell it to destroy windows. What will happen when the app decides that it needs to close the tooltip? It doesn't have the handle of your new window, it has the handle of the old window, which you've destroyed. Time for things to go wrong.
Your plugin system needs to explicitly support replacing the tooltips if you want this to work smoothly. Perhaps an optional part of the plugin framework could be a RequestTooltip function. If it doesn't exist, or returns null, or whatever then the default tooltips are used, otherwise your plugin provided ones are used.

Windows 7 Jump List

I think that is what this is called:
I want to be able to add stuff like that to my program. Such as an open button and other buttons that would execute a method within the app. This is in C#, by the way.
I DID look into the Windows 7 API Code Pack, but it.. doesn't work the way I want. It won't let me execute a method inside my app like I want. It just lets you open other apps.
Is something like this possible?
I think its you who doesnt understand how JumpLists work.
"It just lets you open other apps" Is exactly what it does, nothing else. Thats Windows 7 feature, not API Code Pack limitation. Key point to this is fact, that your application is not running, so WHERE it should execute your method?
Correct implementation would be to make your JumpList run your application with correct parameters and then inside your application Main method invoke different methods depending on those parameters.
Dont forget, even window applications have input parameters, just like console apps.
If you look at Outlook and Messenger, they invoke other commands within the app, so you know it is possible. But as #Euphoric says, the architecture of jumplists is really simple - choosing a destination (eg a file name or URL) results in Windows launching another instance of the app and passing that destination as a command line argument. Choosing a task results in Windows launching that task, which needs to be some other exe.
How to resolve this seeming paradox? The other exe is a helper exe that communicates with the main app. Examples of this are in short supply but I am working on a demo for an early November talk, and will blog it when I have it done. Perhaps this architectural pointer will get you started.
Assign URLs to the jump list items and use an HTTP listener to invoke methods upon your application. Like this URL mapping with C# HttpListener
Additionally, you can go the awekward route and use a shared mutex to make your application single instance only and forward command line arguments across a named pipe. But the http listener is nicer ;)

C# Winform: Is Application.Run() useful if I run a Dialog Form ?

Can I just do in Program.cs
Form1.ShowDialog();
And in Form1:
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
Application.Exit();
}
That is I never use Application.Run() like the default VStudio Code ?
Is there any annoyance to do so ?
I always like to stick with the form class methods. Form.ShowDialog() and Form.Close(). Everything you need is there, including the Form.DialogResult. If you stick to just instantiating your forms and using the methods attached to them, it seems a lot cleaner in the long run. I don't feel you would gain anything from using Application.Run() when running a form dialog.
Yes, ShowDialog will create and run its own message loop. There are actually a lot of different methods you would not even think of that do this.
Application.Exit instructs all running message loops to exit. I do not know enough about your application to make a recommendation either on the usage of this method. But, in mainstream scenarios I think you will find that its useful is limited at best.
There are definitely times when you do not want to use the default code that VS generates regarding Application.Run, but your statement that you never use it is concerning to me.
You can do this but it isn't good design. Program.cs is what starts up the application and contains the smarts of what it means to start and stop the application. The form which it runs is a window that the user interacts with and should just contain that code.
For example, what if you later want to include that form in another application? Well you have to modify it because it calls Application.Exit() which would be problematic. Furthermore, if you have automated GUI unit tests calling Application.Exit() is not good either.
You should just rely on a call to Form.Close() to return control to the caller rather than Application.Exit(). If the caller is Program.cs, well then your application will terminate.

Categories

Resources