473,785 Members | 2,449 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Launching copies of a WinForm app from within itself

I have a WinForm application that, depending on user actions, may spin for a
while doing extensive calculations, showing a progress bar in the meantime.
I would like to be able to launch a second complete copy of the main form so
the user may start a second lengthy calculation if desired.
I have a menu item to "Launch New Workspace" but I am having difficulty
implementing this. I detail my experiments below; any suggestions on the
proper way to do this would be appreciated.
[Environment: WinXP, VS2008, .NET 2.0]

===========
Attempt #1:
===========
This creates a new workspace that works, except that when the first
workspace is tied up doing calculations, this one is locked up as well since
it is in the same thread.

private void LaunchNewWorksp ace()
{
new MainForm().Show ();
}
===========
Attempt #2:
===========
This attempts to create a new thread.

private void LaunchNewWorksp ace()
{
Thread newThread = new Thread(new ThreadStart(New WorkspaceThread Start));
newThread.Start ();
}
private void NewWorkspaceThr eadStart()
{
new MainForm().Show ();
}

During initialization of the new new workspace I get this error:
System.Threadin g.ThreadStateEx ception was unhandled: Current thread must be
set to single thread apartment (STA) mode before OLE calls can be made.
Ensure that your Main function has STAThreadAttrib ute marked on it.

The above error occurs on this statement:
this.myComboBox .AutoCompleteMo de =
System.Windows. Forms.AutoCompl eteMode.Suggest Append;
===========
Attempt #3:
===========
Variation of previous attempt.

private void LaunchNewWorksp ace()
{
Thread newThread = new Thread(new ThreadStart(New WorkspaceThread Start));
newThread.Start ();
}
[STAThread]
private void NewWorkspaceThr eadStart()
{
Application.Run (new MainForm());
}

This resulted in the same error at the same location. Some cursory reading
about the STAThread attribute seemed to indicate it is something that should
not be needed; I am uncertain how to proceed with this.
===========
Attempt #4:
===========
Further research found this pattern, which I am guessing is an older
approach to threading.

private void LaunchNewWorksp ace()
{
MainForm workerObject = new MainForm();
Thread newThread = new Thread(workerOb ject.NewWorkspa ceThreadStart);
newThread.Start ();
}
private void NewWorkspaceThr eadStart()
{
Show();
}
System.InvalidO perationExcepti on was unhandled: Cross-thread operation not
valid: Control 'statusStrip' accessed from a thread other than the thread it
was created on.
===========
Attempt #5:
===========
Double-click on my application icon on my desktop:-)
This works, creating a completely independent process, but is not integrated
into the application as a menu choice as I would like.

Jun 27 '08 #1
7 1920
===========
Attempt #5:
===========
Double-click on my application icon on my desktop:-)
This works, creating a completely independent process, but is not integrated
into the application as a menu choice as I would like.
===========
Attempt #5:
===========
Double-click on my application icon on my desktop:-)
This works, creating a completely independent process, but is not integrated
into the application as a menu choice as I would like.
This code will do exactly the same from you application (create
another instance of your program)

<code>
using System.Diagnost ics;

ProcessStartInf o psi = new
ProcessStartInf o(Application.E xecutablePath);
System.Diagnost ics.Process.Sta rt(psi);

</code>

Although I'd personally suggest a different approach.
Instead of creating a new window, try to run your calculations on a
separate thread while allowing user to continue using the rest of
application.

Micha³
Jun 27 '08 #2
On Jun 21, 5:01 pm, michael sorens <m_j_sor...@new sgroup.nospam>
wrote:
I have a WinForm application that, depending on user actions, may spin for a
while doing extensive calculations, showing a progress bar in the meantime.
I would like to be able to launch a second complete copy of the main form so
the user may start a second lengthy calculation if desired.
I have a menu item to "Launch New Workspace" but I am having difficulty
implementing this. I detail my experiments below; any suggestions on the
proper way to do this would be appreciated.
[Environment: WinXP, VS2008, .NET 2.0]

===========
Attempt #1:
===========
This creates a new workspace that works, except that when the first
workspace is tied up doing calculations, this one is locked up as well since
it is in the same thread.

private void LaunchNewWorksp ace()
{
new MainForm().Show ();

}

===========
Attempt #2:
===========
This attempts to create a new thread.

private void LaunchNewWorksp ace()
{
Thread newThread = new Thread(new ThreadStart(New WorkspaceThread Start));
newThread.Start ();}

private void NewWorkspaceThr eadStart()
{
new MainForm().Show ();

}

During initialization of the new new workspace I get this error:
System.Threadin g.ThreadStateEx ception was unhandled: Current thread must be
set to single thread apartment (STA) mode before OLE calls can be made.
Ensure that your Main function has STAThreadAttrib ute marked on it.

The above error occurs on this statement:
this.myComboBox .AutoCompleteMo de =
System.Windows. Forms.AutoCompl eteMode.Suggest Append;

===========
Attempt #3:
===========
Variation of previous attempt.

private void LaunchNewWorksp ace()
{
Thread newThread = new Thread(new ThreadStart(New WorkspaceThread Start));
newThread.Start ();}

[STAThread]
private void NewWorkspaceThr eadStart()
{
Application.Run (new MainForm());

}

This resulted in the same error at the same location. Some cursory reading
about the STAThread attribute seemed to indicate it is something that should
not be needed; I am uncertain how to proceed with this.

===========
Attempt #4:
===========
Further research found this pattern, which I am guessing is an older
approach to threading.

private void LaunchNewWorksp ace()
{
MainForm workerObject = new MainForm();
Thread newThread = new Thread(workerOb ject.NewWorkspa ceThreadStart);
newThread.Start ();}

private void NewWorkspaceThr eadStart()
{
Show();}

System.InvalidO perationExcepti on was unhandled: Cross-thread operation not
valid: Control 'statusStrip' accessed from a thread other than the thread it
was created on.

===========
Attempt #5:
===========
Double-click on my application icon on my desktop:-)
This works, creating a completely independent process, but is not integrated
into the application as a menu choice as I would like.
Instead of MainForm, you can use another form as the starting form.
From that starting form, you could open multiple instances of the old
main form.
Jun 27 '08 #3
Thanks Piaskal for your reply!

Hi Michael,
I would like to be able to launch a second complete copy of the main form
so the user may start a second lengthy calculation if desired.

In my opinion, you may not need to start a second instance of the
application to start a second lengthy calculation. You can use a
BackgroundWorke r component to do the time-consuming work in a separate
thread.

For more information on how to use the BackgroundWorke r component, see the
following MSDN document:
http://msdn.microsoft.com/en-us/libr...backgroundwork
er.aspx

The solution that Piaskal suggested works perfectly. If you really want to
start a second instance of the application from within the application
itself, you can adopt the solution that Piaskal provided.

Hope this helps.
If you have any question, please feel free to let me know.

Sincerely,
Linda Liu
Microsoft Online Community Support

Delighting our customers is our #1 priority. We welcome your comments and
suggestions about how we can improve the support we provide to you. Please
feel free to let my manager know what you think of the level of service
provided. You can send feedback directly to my manager at:
ms****@microsof t.com.

=============== =============== =============== =====
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscripti...ult.aspx#notif
ications.

Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscripti...t/default.aspx.
=============== =============== =============== =====
This posting is provided "AS IS" with no warranties, and confers no rights.

Jun 27 '08 #4
I agree that a BackgroundWorke r would be appropriate in certain
circumstances; in my particular case it is not the best choice due to other
factors I did not mention (as I wanted to keep the post as short as I could).

So: I am aware of the ProcessStartInf o class, but I would have thought that
I could achieve an equivalent result with threads; I infer from your
responses that this is not the case (or at least not simple). Just for
academic curiosity, is there a short answer as to why?

My real follow-up questions, though, are these:
I tried the approach with ProcessStartInf o and it launched fine, but I
notice that it did *not* read the user.config file that the first instance of
the application used. (Not sure if it read *any* user.config file). Also,
could I somehow attach Visual Studio to the second process for debugging?

Jun 27 '08 #5
Sorry for jumping the gun on my prior post--I found the answers to my two
main questions:
(1) The user.config was different because the first instance was running
app.vshost.exe while the second instance ran app.exe.
(2) I found how to attach and debug existing processes in VS.

That leaves only the minor academic question as to why my attempt with
threads was unsuccessful...
Jun 27 '08 #6
There is nothing academic about why your attempts with threads didn't work.

It's simply that they were, at least, inappropriate.

As you figured out for yourself, Attempt #2 failed because you didn't have
NewWorkspaceThr eadStart marked as an STA thread.

Attempt #3 failed because, although you marked NewWorkspaceThr eadStart as an
STA thread, you also did attempted to start a new main message pump:
Application.Run (new MainForm()) instead of new MainForm().Show ().

As for Attempt #4, workerObject (new MainForm()) was created on the main UI
thread and then you attempted to 'show' it from another thread (newThread).
"michael sorens" <m_********@new sgroup.nospamwr ote in message
news:EA******** *************** ***********@mic rosoft.com...
Sorry for jumping the gun on my prior post--I found the answers to my two
main questions:
(1) The user.config was different because the first instance was running
app.vshost.exe while the second instance ran app.exe.
(2) I found how to attach and debug existing processes in VS.

That leaves only the minor academic question as to why my attempt with
threads was unsuccessful...

===========
Attempt #4:
===========
Further research found this pattern, which I am guessing is an older
approach to threading.

private void LaunchNewWorksp ace()
{
MainForm workerObject = new MainForm();
Thread newThread = new Thread(workerOb ject.NewWorkspa ceThreadStart);
newThread.Start ();
}
private void NewWorkspaceThr eadStart()
{
Show();
}
System.InvalidO perationExcepti on was unhandled: Cross-thread operation not
valid: Control 'statusStrip' accessed from a thread other than the thread it
was created on.
===========
Attempt #5:
===========
Double-click on my application icon on my desktop:-)
This works, creating a completely independent process, but is not integrated
into the application as a menu choice as I would like.

Jun 27 '08 #7
Hi Michael,

Thank you for your reply!
That leaves only the minor academic question as to why my attempt with
threads was unsuccessful...

The error in your solution in the Attempt #4 is apparent. WinForm
programming model doesn't allow cross-thread operation, i.e. a control can
be accessed only by the thread in which it is created.

The solution in the Attempt #3 makes more sense than that in the Attempt
#2, because it sets up a new message loop for the new instance of MainForm.
Note that in both solutions in Attempt #2 and #3 the old and new instances
of MainForm runs in a same process. You can see this in the Processes tab
in the Windows Task Manager.

Unfortunately, OLE calls requests STA mode for the application, so the
solution in the Attempt #3 doesn't work if you have OLE calls in the
application.

Thus, the robustest solution is to start a new process for the application
using the Process class. And in this case, there will be really two
processes running on the machine.

Hope this helps.
If you have any question, please feel free to let me know.

Sincerely,
Linda Liu
Microsoft Online Community Support

Delighting our customers is our #1 priority. We welcome your comments and
suggestions about how we can improve the support we provide to you. Please
feel free to let my manager know what you think of the level of service
provided. You can send feedback directly to my manager at:
ms****@microsof t.com.

This posting is provided "AS IS" with no warranties, and confers no rights.

Jun 27 '08 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

20
3125
by: svend | last post by:
I'm messing with some code here... Lets say I have this array: a1 = ; And I apply slice(0) on it, to create a copy: a2 = a1.slice(0); But this isn't a true copy. If I go a1 = 42, and then alert(a2) I will see 42 there too. I'm doubting, but I was
6
384
by: Brent Stevenson | last post by:
DOtNEt newbie. How do you launch an IE Browser from a winform?
1
2079
by: i | last post by:
Hi, I'm trying to get a seperate class, initialized by a form class, to manipulate certain objects on the form (ex: add to a listbox). The manipulation will occur via a thread that is not the normal WinForm GUI thread. How would I go about doing this? I have this code for cross-thread WinForm manipulation, but only from within the WinForm class:
8
2844
by: Sunil Menon | last post by:
Dear All, We are developing applications in ASP.Net...in one of our applications we would like to use a GridControl...we have tried to use a Server-Side Grid control but found the speed to be an issue...also our clients would like to use a lot of client side events like sorting, searching text, save each row on tab out of a row, use the auto correct feature... after intial r&d we feel that using a Grid Control in WinForms would be a...
4
2241
by: Mike | last post by:
We have a two-pronged application, one is ASP.NET driven and the other is a bunch of WinForms packed into a VB.NET executable. Is there anyways to be able to call that executable from the ASPX page? We had implemented a custom URL handler in the past, but in our next release we cannot require any users to have administrative rights to their machine, so that means they cannot write the necessary registry information to register the URL...
4
1353
by: Ori :) | last post by:
Hi guys, I have a scenario where my application needs to run/start an application that is already installed on my machine. let's say - run an executable "ccc.exe". How do I call this executable from within my application and run it? Thanks!
0
1784
by: microb0x | last post by:
Is there any difference in the way an Access .mdb file is launched from directly double-clicking the file through windows explorer versus using code within another Access file to launch the same file? Here is my situation: I have an application that when launched does a check whether or not
0
3558
by: Hasim AH | last post by:
Hi .. Just getting interested to learn C# and needs help. I want to write C# application so that the program will execute and draw graphics when the user select the drawing menu from the main menu, SigDraw. Here is the codes:- using System; using System.Drawing; using System.Collections;
10
3643
by: Andrew Neiderer | last post by:
I think I am asking the right newsgroup. If not maybe someone could tell me where to ask this "beginner" question. I want to click on an image (.jpg) that launches a Microsoft window (cmd.exe or command.com) which executes some .exe, e.g googleearth.exe. I know this is simple for most of you but I am just starting XHTML. I think it begins with <html> <body>
0
9645
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10325
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10147
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10091
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9950
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8972
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6739
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5381
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4050
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.