Changing the content of a form from outside? - c#

I've got a form called MyForm, and I want to edit it's properties in the middle of the program's execution, from outside of the class itself.
Here's what I got:
static void Main()
{
MyForm main = new MyForm();
main.ShowDialog();
main.Text = "Hello";
}
However, it seems like ShowDialog() just freezes the program until I close the form, so main.Text = "Hello"; won't be executed until I close the form.
I've also tried using main.Show() but it just closes the form after I've executed all the code in my Main() function, so the text "Hello" will only flash quickly.
I would need it so that I can have the form open at all times and change it's controls in the middle of the program's execution, from outside of the class itself.
How can I achieve this? Should I run the form in a different thread or something?

There are multiple questions here, you should try to focus on one at a time, so let me highlight the questions.
Why does my program close when Main exits?
How can I avoid "freezing" the program when showing a form?
How can I access the contents of a form from elsewhere?
Answers:
That's the design of how the lifetime of a program is. When the main thread (running the Main method) terminates, the program closes. Any open forms are closed in the process. Solution is to not allow Main to exit, typically by using Application.Run(main); in your case, showing the form and waiting for it to close.
You use Show and not ShowDialog, but since you have no other form keeping the program open, your program closes. Show returns after showing the form, returning to whatever the program was doing. In your case, the program has nothing left to do, so it terminates.
You need to store a reference to your form somewhere the rest of your program can access it, you can use a static field/property somewhere, or you can pass the form around to the various parts that need it.

First of all, I don't know what is your specific scenario. Perhaps my solution is good for you, but if it isn't, please, try to tell us what exactly are you trying to achieve.
static void Main()
{
var main = new MyForm();
//Initialize a new thread with the `DoSomething()` method
//and pass the form as a parameter
var thread = new Thread(() => DoSomething(main)) {IsBackground = true};
thread.Start();
main.ShowDialog();
}
static void DoSomething(MyForm main) {
//Update the form title
main.Text = "Hello";
//Wait one second
Thread.Sleep(1000);
//Update the form title again
main.Text = "World";
}

Related

Check visibility of the child process window

I have two .NET applications:
parent-app.exe (WPF)
child-app.exe (WinForms)
The first application starts the second one
parent-app.exe → child-app.exe
by means of the class System.Diagnostics.Process.
When user clicks a button on the interface of the parent-app.exe, I start the process of child-app.exe immediately. Because child-app.exe is a .NET application, is takes some time before user could see the window (especially, on slow systems).
I want to show the user an intermediate (possibly dialog) window from parent-app.exe. This dialog window should say that user action is being processed and he should wait for the window of child-app.exe to show up.
Questions:
How can I check from parent-app.exe visibility state of the window of child-app.exe?
Here is the longer question. How would you implement this system of showing intermediate window by taking into account the restriction
that both programs use .NET?
As suggested here, you can try calling the Process.WaitForInputIdle method to wait for the MainWindowHandle to be created or periodically calling Process.Refresh and check if MainWindowHandle returns a valid handle. Perhaps this is enough for you, otherwise you can get additional information with the handle. In WinForms you could probably do something like this:
Form window = (Form)Control.FromHandle(process.MainWindowHandle);
I suspect there are similar solutions for other frameworks.
Update
I wrote this small sample, it is untested and I don't know if it works reliably (it may deadlock), but it should hint at some things you can try:
namespace SomeNS
{
using System.Diagnostics;
using System.Windows.Forms;
public static class SomeClass
{
static void SomeMethod()
{
Process process = Process.Start("child-app.exe");
// YourDialog is your dialog implementation inheriting from System.Windows.Window
YourDialog dlg = new YourDialog();
dlg.Loaded += (sender, e) =>
{
process.WaitForInputIdle();
Form window = (Form)Control.FromHandle(process.MainWindowHandle);
// Do something with the child app's window
dlg.Close();
};
dlg.ShowDialog();
}
}
}

MediaElement freezes upon launch of video

I'm working on a project that is designed to play both audio and video files through a WPF Window through a MediaElement. This is the xaml for the window:
<Window x:Class="HomeSystem_CSharp.MediaWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MediaWindow" MinHeight="480" MinWidth="720" WindowStyle="None" ResizeMode="NoResize" Visibility="Visible" Cursor="None">
<Grid Background="Black">
<MediaElement LoadedBehavior="Manual" HorizontalAlignment="Stretch" Name="video" VerticalAlignment="Stretch" Cursor="None" MinHeight="480" MinWidth="720"/>
</Grid>
</Window>
This creates the window with no borders, that I plan on full-screening in the future. For now though, I want more room on my desktop. Here is my code for controlling my MediaElement:
private bool playing = false;
public MediaWindow(string dir)
{
InitializeComponent();
video.Source = new Uri(dir);
play();
}
public void play()
{
if (playing)
return;
if (!this.IsVisible)
this.Show();
video.Play();
playing = true;
}
This MediaWindow is created outside of the object, just by a simple MediaWindow mw = new MediaWindow("C:\\test.mp4");
No matter how i've moved stuff around in my code, upon launch EVERY time the GUI is unresponsive, but sound plays. I can hear the video in the background, but there is a broken window on my screen. Just a black box.
The biggest issue is that just the other day it was working fine, and suddenly it broke, and I have no clue what happened. I'm kinda new to c#, so I dont know a TON about what's going on, but I've worked with java for several years so I'm not totally new. Can anyone point out what I'm doing wrong? i can provide any other details but I think i got everything necessary to answer. Thank you for any help, this has been bothering me all day with no fix!
EDIT: Turns out, if I use
public void play()
{
if (playing)
return;
//if (!this.IsVisible)
// this.Show();
video.Play();
new Application().Run(this);
playing = true;
}
instead, it will run the GUI. However, that hangs up the console. Originally I fixed that hang up by using this.Show(), but now that's not working. I know that moving the whole project into a WPF project would fix this, however I'm really trying not to for other reasons. Only win32 for now. Any ideas why this is happening and how to fix it? I do have [STAThread] over my main function if that makes a difference.
EDIT 2:
This video file I'm playing is movie length, and runs perfectly in any other software to prevent that from being an issue with development. As for the MediaWindow creation. What I did is made a win32 console project and set up the user commands there. I then made a new WPF project, and created an xaml gui window. I took those code files, and copied them into the win32 project, and call it to launch in the main method with the MediaWindow mw = new MediaWindow("C:\\test.mp4"); I did it this way because for now I'm trying to keep away from using a pure WPF application, and because I'm kinda new to C# so I wasnt sure how to create the window I wanted without my copy paste method.
No matter how i've moved stuff around in my code, upon launch EVERY time the GUI is unresponsive, but sound plays.
I've managed to reproduce this. One important thing missing in your description is the exact way you create and show the window in your main() method. For example, the following freezes the video leaving the sound playing:
[STAThread]
static void Main(string[] args)
{
var w = new MediaWindow();
w.Show();
Console.ReadLine();
}
The next one "freezes" the console until you close the window:
[STAThread]
static void Main(string[] args)
{
var w = new MediaWindow();
w.ShowDialog();
Console.ReadLine();
}
And this gives you both working:
static void Main(string[] args)
{
var thread = new Thread(ShowMediaWindow);
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
while (true) // Just to test console working
{
Console.Write("\r" + DateTime.Now);
Thread.Sleep(100);
}
}
static void ShowMediaWindow()
{
new MediaWindow().ShowDialog();
}
As you can see, the console and the WPF window simply can't work properly in a single thread.
The window class is as simple as this, by the way (the XAML is mostly the same as yours):
public partial class MediaWindow : Window
{
public MediaWindow()
{
InitializeComponent();
video.Source = new Uri(#"C:\video\test.asf");
Play();
}
public void Play()
{
video.Play();
}
}
I guess that'll do for showing a video player window from console.
OK, the whole hybrid console/GUI thing is a new one on me but I'm just going to assume there's a real need to do things that way.
The Application.Run method doesn't return until the application closes. That's why your console is locked up.
Don't create the Application object inside the window. Do it externally. Also, spawn another thread to kick off video playback. This will leave your console responsive.
I'm not gonna get heavy-duty into describing threading and delegates and so forth... you can look that up if you want. I'm just gonna go over what you need to do for this specific example. Somewhere in the class that launches the video, but not in a method, define a delegate type like this:
delegate void LaunchVideo(String s);
A delegate is essentially kind of a pointer to a function with a certain definition of return value and parameters. Here we've defined the delegate type as a function that takes a String parameter and returns nothing. Next, at the point in your code where you want to play the video, do this:
LaunchVideo lv = new delegate(String vidfile)
{
Application app = new Application();
app.Run(new MediaWindow(vidfile));
};
IAsyncResult result = lv.BeginInvoke( "C:\\vid.mp4", myVideoCompleted, null );
This creates the delegate variable and points it at an anonymous function that creates the app and launch video playback. Then it calls the delegate's BeginInvoke method, which is part of the basic delegate class. This spawns a new thread running in the function pointed to by the delegate.
Note that calling Application.Run with a window parameter like this will open the window but it won't call the play() method. You may want to move that code to the constructor, or add a call to it in the constructor.
Be aware that your main thread cannot safely call methods in objects created in the invoked thread unless you use the lock function to make things thread safe.
If you need "open" and "play" to be separately controlled events which are both invoked by the console then you'll have to figure out a means to pass messages from the console thread to the window thread.
The parameter list for BeginInvoke always starts off with whatever parameters are expected by the function you're invoking. So in this case, that's the string with the video filename. Next is the name of a callback function which will be called when the invoked function exits. It's a void function that takes an AsyncResult parameter, like this:
void myVideoCompleted(AsyncResult result)
{
// Do whatever here... Be aware this is still on the other thread
}
You can use 'null' instead of a function name, if you don't need anything called at the end. Be aware that if you do use a callback function, it runs on the new thread started by BeginInvoke, not the thread that called it.
The last parameter to BeginInvoke is an object that will be passed through to the callback function via the AsyncState member of the AsyncResult parameter. You can pass 'null' if you're not using a callback or if you have no parameters which will be needed by the callback.
You can also call the EndInvoke method of the delegate to get back any results that may've been returned by the function. However, be aware that this will block if the invoked function isn't finished yet. In this case you have no results to worry about.

Windows Form dies right after the constructor is done

I'm currently writing an IRC bot/client and I have stumbled upon a small problem. Every channel is to be displayed in a separate window with its own set of controls. I have created an appropriate window class ChanWindow:
public partial class ChanWindow : Form
{
string Chan;
string Username;
IRCBot Caller;
public ChanWindow(string channame, string uname, IRCBot caller)
{
Caller = caller;
Caller.Join(channame);
InitializeComponent();
Chan = channame;
Name = Chan;
Username = uname;
}
//various functionalities required for window use
}
I'm storing the window objects in a ConcurrentDictionary<string, ChanWindow>, because there is (supposed to be) a separate thread sending appropriately edited messages to windows. They are all initialized in a loop:
foreach (string chan in Chanlist)
{
Chans[chan] = new ChanWindow(chan, Name, this);
Chans[chan].Show();
}
Where Chanlist is a List<string> of channels to join.
Having witnessed the windows die shortly after the program starts, I put a breakpoint in the line Username = uname; of ChanWindow constructor and noticed it being tripped immediately before the window's death.
My main question is: what is the cause and how can I avoid it? Is using a Dictionary a good idea? Should I build some sort of wrapper/container class which would handle the window's functionality?
I suspect you don't have
Application.Run(new ChanWindow());
in your main entry point (Program.Main() by default).
If you don't make the main GUI thread Show the form, and wait for it to close, nothing will stop the thread from completeing and your application closing.
If you want to start the message loop independently you will still need to call Application.Run() so the main thread will start handling events. If you call it without a parameter the message loop won't stop automatically so you'll have to call Application.Exit() explicitly when you want the message loop to stop. Then the main thread will then continue to the end of the program and end.
You could just do this to your code,
foreach (string chan in Chanlist)
{
Chans[chan] = new ChanWindow(chan, Name, this);
Chans[chan].Show();
}
Application.Run();
but, if you want to automatically exit the application you could inherit your own ApplicationContext, as outlined in the already linked MSDN documentation, and pass that to Application.Run(), that is what its for after all.

Cross-threading forms in C# with Mono

I'm creating an application that uses .Net and Mono, it uses cross-threaded forms as I was having bad response from the child windows.
I created a test program with 2 forms: the first (form1) has a single button (button1) and the second (form2) is blank, code snippet below.
void openForm()
{
Form2 form2 = new Form2();
form2.ShowDialog();
}
private void button1_Click(object sender, EventArgs e)
{
Thread x = new Thread(openForm);
x.IsBackground = true;
x.Start();
}
This works fine in .Net, but with Mono, the first window will not gain focus when you click it (standard .ShowDialog() behaviour) rather than .Show() behaviour as .Net uses.
When I use .Show(), on .Net and Mono the window just flashes then disappears. If I put a 'MessageBox.Show()' after 'form2.Show()' it will stay open until you click OK.
Am I missing something in that code or does Mono just not support that? (I'm using Mono 2.8.1)
Thanks in advance, Adrian
EDIT: I realised I forgot 'x.IsBackground = true;' in the code above so child windows will close with the main window.
It's almost never the right thing to do in a Windows app to have more than one thread talk to one window or multiple windows which share the same message pump.
And it's rarely necessary to have more than one message pump.
The right way to do this is either to manually marshal everything back from your worker threads to your Window, using the 'Invoke' method, or use something like BackgroundWorker, which hides the details for you.
In summary:
Don't block the UI thread for time-consuming computation or I/O
Don't talk to the UI from more than one thread.
If you use Winforms controls, you shold "touch" the object always in main UI thread.
And at least - calling new Form.ShowDialog() in new thread does not make sense.
EDIT:
If you want easy work with Invoke/BeginInvoke you can use extension methods:
public static class ThreadingExtensions {
public static void SyncWithUI(this Control ctl, Action action) {
ctl.Invoke(action);
}
}
// usage:
void DoSomething( Form2 frm ) {
frm.SyncWithUI(()=>frm.Text = "Loading records ...");
// some time-consuming method
var records = GetDatabaseRecords();
frm.SyncWithUI(()=> {
foreach(var record in records) {
frm.AddRecord(record);
}
});
frm.SyncWithUI(()=>frm.Text = "Loading files ...");
// some other time-consuming method
var files = GetSomeFiles();
frm.SyncWithUI(()=>{
foreach(var file in files) {
frm.AddFile(file);
}
});
frm.SyncWithUI(()=>frm.Text = "Loading is complete.");
}

how to run a winform from console application?

How do I create, execute and control a winform from within a console application?
The easiest option is to start a windows forms project, then change the output-type to Console Application. Alternatively, just add a reference to System.Windows.Forms.dll, and start coding:
using System.Windows.Forms;
[STAThread]
static void Main() {
Application.EnableVisualStyles();
Application.Run(new Form()); // or whatever
}
The important bit is the [STAThread] on your Main() method, required for full COM support.
I recently wanted to do this and found that I was not happy with any of the answers here.
If you follow Marc's advice and set the output-type to Console Application there are two problems:
1) If you launch the application from Explorer, you get an annoying console window behind your Form which doesn't go away until your program exits. We can mitigate this problem by calling FreeConsole prior to showing the GUI (Application.Run). The annoyance here is that the console window still appears. It immediately goes away, but is there for a moment none-the-less.
2) If you launch it from a console, and display a GUI, the console is blocked until the GUI exits. This is because the console (cmd.exe) thinks it should launch Console apps synchronously and Windows apps asynchronously (the unix equivalent of "myprocess &").
If you leave the output-type as Windows Application, but correctly call AttachConsole, you don't get a second console window when invoked from a console and you don't get the unnecessary console when invoked from Explorer. The correct way to call AttachConsole is to pass -1 to it. This causes our process to attach to the console of our parent process (the console window that launched us).
However, this has two different problems:
1) Because the console launches Windows apps in the background, it immediately displays the prompt and allows further input. On the one hand this is good news, the console is not blocked on your GUI app, but in the case where you want to dump output to the console and never show the GUI, your program's output comes after the prompt and no new prompt is displayed when you're done. This looks a bit confusing, not to mention that your "console app" is running in the background and the user is free to execute other commands while it's running.
2) Stream redirection gets messed up as well, e.g. "myapp some parameters > somefile" fails to redirect. The stream redirection problem requires a significant amount of p/Invoke to fixup the standard handles, but it is solvable.
After many hours of hunting and experimenting, I've come to the conclusion that there is no way to do this perfectly. You simply cannot get all the benefits of both console and window without any side effects. It's a matter of picking which side effects are least annoying for your application's purposes.
Here is the best method that I've found:
First, set your projects output type to "Windows Application", then P/Invoke AllocConsole to create a console window.
internal static class NativeMethods
{
[DllImport("kernel32.dll")]
internal static extern Boolean AllocConsole();
}
static class Program
{
static void Main(string[] args) {
if (args.Length == 0) {
// run as windows app
Application.EnableVisualStyles();
Application.Run(new Form1());
} else {
// run as console app
NativeMethods.AllocConsole();
Console.WriteLine("Hello World");
Console.ReadLine();
}
}
}
It´s very simple to do:
Just add following attribute and code to your Main-method:
[STAThread]
void Main(string[] args])
{
Application.EnableVisualStyles();
//Do some stuff...
while(!Exit)
{
Application.DoEvents(); //Now if you call "form.Show()" your form won´t be frozen
//Do your stuff
}
}
Now you´re fully able to show WinForms :)
You can create a winform project in VS2005/ VS2008 and then change its properties to be a command line application. It can then be started from the command line, but will still open a winform.
All the above answers are great help, but I thought to add some more tips for the absolute beginner.
So, you want to do something with Windows Forms, in a Console Application:
Add a reference to System.Windows.Forms.dll in your Console application project in Solution Explorer. (Right Click on Solution-name->add->Reference...)
Specify the name space in code: using System.Windows.Forms;
Declare the needed properties in your class for the controls you wish to add to the form.
e.g. int Left { get; set; } // need to specify the LEFT position of the button on the Form
And then add the following code snippet in Main():
static void Main(string[] args)
{
Application.EnableVisualStyles();
Form frm = new Form(); // create aForm object
Button btn = new Button()
{
Left = 120,
Width = 130,
Height = 30,
Top = 150,
Text = "Biju Joseph, Redmond, WA"
};
//… more code
frm.Controls.Add(btn); // add button to the Form
// …. add more code here as needed
frm.ShowDialog(); // a modal dialog
}
This worked for my needs...
Task mytask = Task.Run(() =>
{
MyForm form = new MyForm();
form.ShowDialog();
});
This starts the from in a new thread and does not release the thread until the form is closed. Task is in .Net 4 and later.
You should be able to use the Application class in the same way as Winform apps do. Probably the easiest way to start a new project is to do what Marc suggested: create a new Winform project, and then change it in the options to a console application
Its totally depends upon your choice, that how you are implementing.
a. Attached process , ex: input on form and print on console
b. Independent process, ex: start a timer, don't close even if console exit.
for a,
Application.Run(new Form1());
//or -------------
Form1 f = new Form1();
f.ShowDialog();
for b,
Use thread, or task anything,
How to open win form independently?
If you want to escape from Form Freeze and use editing (like text for a button) use this code
Form form = new Form();
Form.Button.Text = "randomText";
System.Windows.Forms.Application.EnableVisualStyles();
System.Windows.Forms.Application.Run(form);

Categories

Resources