How to prevent the Form from opening Multiple Times - c#

I have a application in which i have several forms. In that forms, I have a System Settings form. I have to open this form from the menu as well as a shortcut created on the desktop.
I am able to open the form from 2 places individually. But the problem is, It's opening two separate instance of the same form. it means, first, i have clicked on menu to open the form.Now my Form instance is created and it is displayed on the screen. But whenever i click on my desktop icon, It's creating another instance of the same form instead of displaying the same form. . So it means it's displaying two instances of the same form.
But i have display one form only. I have tried and googled in the net also. I didn't find any information.
Can anybody please help me to fix this issue. Any kind of suggestion will be really helpful to me.

You need a single instance. This construct is already available within the .Net framework. Just check out this post from Hanselman.
Note: I know that the namespace of this class is VisualBasic. But that shouldn't hinder you to use it in your C# application. It's just the name of a namespace. It doesn't meant anything about its functionality. (Microsoft had it better named Foo. In that case it would be much more popular.)

Sounds to me, that you need a mutex to control that only one application instance is running at a given time.
See http://iridescence.no/post/CreatingaSingleInstanceApplicationinC.aspx for further details

You have to implement some kind of locking mechanism to allow only one instance of your program running. I guess your System Settings program could check if other instances are running on computer on program launch, if so terminate, otherwise start a new instance.

To throw in one more link, this post seems to cover (my understanding of) what you are trying to do.
http://dotnetperls.com/single-instance-windows-form

I have used semaphor concept to control this. Whenever the form is opened i am writing an entry into registry. Once the form is closed i am removing this entry.
So, whenever i try to open the form, it will check the registry entry. Based on that it will open the form.

Sounds like you need a modified version of the Singleton design pattern. Try having a public static method within the class that internally calls the constructor for the form. Then as someone suggested use a counter variable to keep track of how may times that static method is called thus giving you a metric you can use to ensure only the desired number if instance are created.

Related

Single Instance per Machine of a WPF Application

I have created a taskbar application that I want to ensure that one and only one instance is running. In an article called, WPF Single Instance Best Practices, Evan Wondrasek posted a great answer and I have added it to my application. This appears to work really well with one small exception.
When I implemented this I have lost my splash screen and I do not know why. Can anyone explain why my splash screen no longer works and how I might get the splash screen working again? I used a simple PNG file and marked its properties as a SplashScreen. I am beginning to think I may need to do something with the SplashScreen class to fix this.
TIA, Doug
By implementing the answer in the link you supplied, you replaced the Main function & startup object of your application. You will need to create the SplashScreen object yourself now, put this inside your own Main method:
SplashScreen splashScreen = new SplashScreen("images/logo.png");
splashScreen.Show(true);
See this link for more information: http://social.msdn.microsoft.com/Forums/vstudio/en-US/33894287-101a-4c9f-8c6a-f0452ab4ced0/splash-screen-not-displaying-anymore-on-startup?forum=wpf

Open a file only one time for a program (like MS Word) in C# 4.0 Winform

I am developing a desktop app (C# 4.0 Winforms) where one of the requirements is that the program can be open more than one time. However, I don't want the users to be able to open a given document more than one time (bad things can happen).
Basically I want it to function similarly to MS Word (at least the newer versions) where if you try to open a doc that is already open it takes you to the instance of the program that already has that doc open.
I spend most of my time doing web development, so there might be some easy solution that I just don't know about.
So I really have two different needs.
1) Keep the file from being opened more than one time
2) If they attempt to open it again, bring the instance to the fore ground.
There are a couple of ways I can think of to handle #1, but I'm curious how other people have solved this issue.
I actually don't really have any idea where to even start trying to get #2 to work without making some master form/process that stays open and creates the child programs. IE create another form that actually controls the opening and closing of the current program's main forms, so it would be more of a "tabbed" experience than an actual multiple window experience. More like an old style MDI (which would still leave issue #1).
Any help here (sites to read, namespaces to look at, etc...) would be greatly appreciated.
Edit - I see that this has been marked as a duplicate and that the "duplicate" is at top of the page. One of my requirements is that the program HAS to be able to be open multiple times. Did you guys even read the post? Can some one else come in and vote to reopen the question.
Further Edit - I went with the Mutex idea for to keep the program from opening the same document multiple times. I never did find an easy way to figure out which instance of the program had the document open and bring it to the front, so I gave up for now and just pop a message box telling them it is already open. Named Pipes seemed a bit of overkill for this as it isn't exactly what I want to do and would involve a lot of overhead (and WCF is not the easiest thing in the world), so any further help would be appreciated.
You are asking about mutexes. In Windows you can create a MUTEX (mutually-exclusive flag) so even if second instance of the process opens it tries to create mutex and then fails. Mutexes are OS-wide global vars (sort of) for this purpose and used for IPC/coordination.
Another way would be this - create a window with class name (class as in windows API not as in C# or C++) that has document name embedded and use FindWindow() function to first see if such a window already open. Then you can SendMessage(HWND) to snd that window a message to bring it to front, so if user clicks in Explorer "myfile.doc" and it is already open - you just bring it to front.
APIs to look at (from my brain ram, how do I remember this stuff?):
CreateMutex() / OpenMutex()
FindWindow() / CreateWindow()
SendMessage() / PostMessage()
ShowWindow()/ SetWindowPosition()/BringWinToTop()
I suspect that there are dozens of ways to approach this, but here is how I would approach it:
Only have a single instance of the application and open each of the requested documents in a new window within the application.
This will take a little coordination since subsequent documents that are opened will cause a new instance to be created, but you could setup an interprocess communication mechanism (such as a named pipe) that the first instance of the application creates and subsequent instances check for.
If they find that the IPC exists, they pass the requested file name to the first app instance (which opens the specified file), and then terminate.
Here is a good article on named pipe usage from Microsoft: How to: Use Named Pipes for Network Interprocess Communication

C# - Control another application's windows using Thoughtworks White

I'm creating a C# program and I need to control another application. I found this
example, but it doesn't really work for me (or at least I can't make it work).
1) The application is already running (so I can't use Application application = Application.Launch("foo.exe");
2) It has a textbox and I need to read what's written in it.
3) Then I want to press one of its buttons (This can be done with that: Button button = window.Get<Button>("save"); button.Click();
I also searched Google, but I didn't find anything working.
Can you help me? Thanks in advance.
The documentation doesn't mention it, but Application.Attach() allows you to access a program that is already running. From there, I would expect everything would work as documented.

What pattern use in WPF dekstop app for login window and main application window?

First of all, we are in C#, WPF, desktop application (can be .NET 3.5).
I need to show login window when application starts, if login succeeds, hide login window and show main app window. In addition, when the main window is closed, one should see login window again. If login window is closed, application quits.
Bonus to make it harder: when "Remember user" option checked, login window is skipped and user is logged in automatically, showing the main window instatly. (please do not think about how the option is stored, assume you just know it and have the value in variable).
What is meant to be the application startpoint (means which window is considered to be in app.xaml StartupUri property)?
How would you solve architecture? Is the best way to use App_Startup event and show some window from that point?
What type of App.ShutdownMode would you use? And how would that work? You can use "OneLastWindowClose", "OnMainWindowClose" or "OnExplicitShutdown". What is your choice and why?
In general, I am interested in "what calls what, what is application 'root', what invokes closing the application".
I already have a solution for my problem that works, but I am interested, if any of you have met this problem and how have you solved it? I will gladly share my approach, but I don't want to limit your ideas in the first place.
Thank you for your contribution.
P.S.: I am using MVVM framework, that makes it just a little more messy, but the point stays. I also use Ninject as IoC, but this issue still of course stays on. I did not mention these information to make the question as clear as possible. I also have to handle exceptions (communication with server or db during the login may fail), and to make it really interesting, I must show interactive 'splashwindow' indicating what application does (loading, communication with server, autologin). But please stay away from these requirements at the moment, we can discuss them later.
I'm going to repeat your questions as I understand them, you can correct me where I am missing something. Also, I'm rather new to the whole M-V-VM thing, so take my advice with a grain of salt. The best way I know how to learn is to throw out my ideas and have them corrected.
You want to know things
1) Where should the logic exist to decide where to show the login or main window
2) Which shutdown mode to use
3) What is application root
1)
I believe the decision to show a login or auto login is business logic, thus should live in the Model of your M-V-VM framework. Once that logic is implemented, the view can display whichever window is required by querying the Model.
I assume your application has an App.xaml and App.cs file which runs when the application is executed. You can override OnStartup within App.cs and display whichever window is necessary, based on the results of the business logic (which are learned from using some object in your Model).
2)
For shutdown model, I'd probably go with OnLastWindowClose, but I have no idea how many windows your application is using. I assume only the two you mentioned (login and main).
3)
What is application root? I would argue that your Model is really the application root, in that it holds all of the important stuff (view is user interface to the model, view model is state for the view). So, when it comes to what is the root or essence of your application, I would argue it is some set of objects in your model.
What calls what? That will all depend on what you're trying to accomplish. In general, I avoid having the view model know anything about the view. Both view and view model can be aware of the model. In certain cases, you'll want to make use of Ninject as a service manager in order to inject a view into the view model (without forcing the view model to depend on the view).
An entirely different approach would be to avoid a log in window altogether and display a login method in the main window. You'll still need some Model object to tell you when to show the login prompt, but you won't have to worry about juggling windows. Honestly, I'd probably go that route. WPF provides us with a lot of interesting and sexy ways to accomplish that task.
The Application object is the root of any WPF project. You are correct that you can handle the App_Startup event - depending on what you need to do at startup, of course.
Depending on whether you need a more complex navigation framework or the application will be forever limited to the scenario you described, you can go a multitude of ways from there.
What I'm doing in the applications I work on is I create a Navigator object that handles navigation both between different windows and inside windows, then I simply call Navigator.Navigate(new MyViewModel(), NavMode.ReplaceWindow); which closes the previous 'main' window (if any is open) and displays a new one, setting the contents to the instance of my ViewModel. The ViewModel is then displayed using the correct templates. I can also use NavMode.ReplaceUserControl which replaces the contents of the current 'main' window, or NavMode.OpenModalWindow which displays a modal dialog. My ShutdownMode is set to OnLastWindowClose, since I can always call App.Shutdown() if I want to close regardless of the open windows.
Of course, when you replace windows you need to make sure to instantiate (not show, just instantiate) the new window before closing the old one, to avoid application shutdown because you have no more windows.
You could do something similar, but it's just an idea and it's tailored specifically for my requirements.

Application using multiple windows forms

I am (still) writing a small application which requires me to use several windows forms to show to the user.
Some of the forms just show progress messages while the application performs tests using several external devices.
The forms will usually be used in order (see below) but there may be some errors picked up from the devices, in which case an Error Reporting form will be used. The user will have the option to go back to the beginning or to the 2nd test (the 1st test takes 30 mins to perform). The error report can be invoked from any other form.
Also, the final form has the option to go back to the beginning to perform the tests on a new device.
Obviously this would cause the suite of forms to get rather tangled up. if it were used for several devices with errors etc.
So am I have a few questions.
Am I using the forms correctly and if so, how do I pass control from one form to the next one without having to go back to the original form, if that makes sense ?
Can I still have access to all variables created in preceding forms, or should I create all the variables in the initial form setup ?
Or should I have all the processing within one parent form and simply "show" the other forms as part of the procedure ?
I hope this doesn't sound too stupid, but I havent used multiple forms in C# yet. The steps are ALSO dependent on each other.
The following is the usual flowchart of forms, with PRGERREP being called from any form (more or less).
PRGSTART
PRGDEFAULT
PRGTEST1
PRGTEST2
PRGTEST3
PRGTEST4
PRGMANUAL
PRGFINALE
PRGERREP
Any help or advice would be most appreciated.
Please try to focus more on the question, not the context.
Even though i don't know exactly what you want, you should check out MDI Applications.
Basically you have a parent form with several child forms. Should your tests be finished you can BringToFront() the corresponding child window from the parent form.
I question the requirement to use multiple forms for this. Most applications show all information for a task; progress, tests, errors, messages, et al. in a single window, not multiple windows. Web browsers and office applications are very complex programs and manage to show all task information in a single window.
The fact that you are trying to "pass control" between multiple forms makes me suspect using multiple windows is a bad design. Look at the windows on your screen now; each one is a self-contained environment and does not need to "pass control" between each other.
If you are trying to make the user do something in sequence, handling errors before going on to the next step and allowing the user to "go back to the beginning", a wizard-like design may be better.
Create a single form with fields and buttons for the first task. Clicking a button redraws the form with fields and buttons for the next task, and buttons to go back or start over. This can be done more easily than creating a bunch of separate forms and trying to synchronize data between them.
Consider inheriting from an ApplicationContext to implement this logic in your application. See here and here.

Categories