Easy Winforms question(s)

Status
Not open for further replies.

hanser

Ars Legatus Legionis
43,855
Subscriptor++
Update: new question here.

I'm writing a very basic text editor (think Notepad with a few more features). When a user hits Ctrl+N or File->New, a blank document is created in a new window, much the way you'd open a new browser window.

The problem is, if the user clicks the close button in the upper right with more than one window open, all form windows are closed, not just the current one.

The way the new form functionality is done is:

Code:
private void newToolStripMenuItem_Click(object sender, EventArgs e)
{
	frmMain NewDocument = new frmMain();
	NewDocument.Show();
}

The way the exit functionality is handled is:

Code:
protected override void OnFormClosing(FormClosingEventArgs e)
{
    if (!isNewDocument && !isSaved())      // Pre-existing document, not saved
    {
        var result = MessageBox.Show("Do you want to save your changes?", PROGRAM_NAME, MessageBoxButtons.YesNoCancel);
        if (result == DialogResult.Yes)
            SaveFile();
        else if (result == DialogResult.No)
        {
            initialText = txtText.Text;
            this.Close();
        }
        else if (result == DialogResult.Cancel)
            e.Cancel = true;
    }
    else if (isNewDocument && !isSaved())   // New document, not saved == Save As
    {
        var result = MessageBox.Show("Do you want to save your changes?", PROGRAM_NAME, MessageBoxButtons.YesNoCancel);
        if (result == DialogResult.Yes)
            SaveFileAs();
        else if (result == DialogResult.No)
        {
            initialText = txtText.Text;
            this.Close();
        }
        else if (result == DialogResult.Cancel)
            e.Cancel = true;
    }
}

this.Close() closes all forms, which leads me to believe that maybe the way I'm creating a new document is probably not The Right Way. If this is the case, what is the right way?
 

lobobo

Ars Scholae Palatinae
778
I'm confused, why are you calling Close()? Have you ever tried removing it to see if that would solve your problem?

I don't see why you need to call Close() being that the event is firing because the form is already on its way to closure to begin with, it's implied since this event is firing and this code is executing. Once this event finishes executing the form closes. So why call Close()? You seem to agree with me because you omitted Close() for the Save path, but you included it in the Don't Save path for some reason. If I'm understanding your intent, of the three paths possible, only two of them result in form closure, which is why you cancelled the close event for the cancel path. Alright, but in the other two paths Save and Don't Save, both should result in form closure, yet you've only called Close() in the Don't Save path. Why? Shouldn't it close the same way it would in the Save path except the actions you do before closure (such as setting the initialText)?

I just tested that code, leaving this.Close() in results in an infinite loop with that message box because this event is fired again after this.Close() is called. Unless you have some code in there to break this loop that you haven't posted, I don't know why it's closing all forms for you. Removing this.Close() solves the infinite loop problem and that single form alone is what closes which is what I assume you are looking for.
 

hanser

Ars Legatus Legionis
43,855
Subscriptor++
No, which is another problem (which will presumably be solved when I get the all forms closing problem straightened out). I hadn't mentioned it, because I suspect I'm doing something The Wrong Way, in which case doing it the right way will sort things out.

Edit: Just discovered something.

When I Ctrl+N, I can close the second form, and it won't close the first. If I close the first form, they all close, whether that's two forms or 100.

If I spawn five forms (tap Ctrl+N repeatedly), I can close any of the forms, except the first, and they have no bearing on the forms that followed after, even though each newly-spawned form takes focus, and I'm invoking the code from that form.
 
The application context is tied to the first instance of main form by default in winforms applications (see Program.cs and how the main form is launched in main()). When you close that instance, the context shuts down the application.

While I haven't done it myself, it looks like you need to implement your own ApplicationContext similar to outlined here:

http://msdn.microsoft.com/en-us/library ... ntext.aspx

[Edit]
Ahh, screw it - here's a simplified version:

Code:
    class AppCtx : ApplicationContext
    {
        public AppCtx()
            : base()
        {
            CreateNewForm();
        }


        private static int FormCount = 0;

        public static void CreateNewForm()
        {
            Form1 newFrm = new Form1();
            newFrm.FormClosed += new FormClosedEventHandler(newFrm_FormClosed);
            newFrm.Show();
            FormCount++;
        }

        static void newFrm_FormClosed(object sender, FormClosedEventArgs e)
        {
            FormCount--;
            if (FormCount == 0)
            {
                Application.ExitThread();
            }
        }

    }

and in Program.cs, replace the Application.Run() line with this:
Code:
            Application.Run(new AppCtx());


Then, when you want a new copy of the form:
Code:
            AppCtx.CreateNewForm();
 

hanser

Ars Legatus Legionis
43,855
Subscriptor++
Thanks El Guapo, that worked perfectly!

In terms of the class AppCtx, what is the "correct" way of adding it to my project? Right now it's sitting inside frmMain.cs, after the definition and all of the code contained in the frmMain class. This works, I can pop open new forms and whatnot with no problem, but it doesn't *feel* right. Messy somehow. Like maybe it should go inside its own .cs file?

Edit: Along similar correctness lines, is it better practice to do this.Close() or is just doing Close() OK? I know they both do the same thing, but which is "better"?
 
hanser":2jud3dhp said:
Thanks El Guapo, that worked perfectly!

In terms of the class AppCtx, what is the "correct" way of adding it to my project? Right now it's sitting inside frmMain.cs, after the definition and all of the code contained in the frmMain class. This works, I can pop open new forms and whatnot with no problem, but it doesn't *feel* right. Messy somehow. Like maybe it should go inside its own .cs file?

Edit: Along similar correctness lines, is it better practice to do this.Close() or is just doing Close() OK? I know they both do the same thing, but which is "better"?

Both questions come down to coding style and convention, and often spawn internet nerd range arguments spanning hundreds of pages :p

I tend to add small helper classes within the same file as the main class that uses it. When a class is used by multiple pieces of the project (i.e. multiple forms or referenced from multiple .cs files), then I will place it into it's own .cs file. In cases where I have a bunch of small helper classes, I make a MiscClasses.cs file that has a bunch of widely-used helper classes.

With some larger, more involved classes, I'll put those in their own source file just for organizational purposes.

Some say you should only ever put one class in each source file - I find this a overly burdensome rule, as it leads to zillions of source files.

When I prototyped this up, I put AppCtx in its own .cs file.

As for the "this" convention, use it if you need the reminder that you're calling a method on the current instance, or if you've got multiple things named the same or close to the same within a context and you want to be unambiguous about what you're exactly calling. Personally, I almost never use "this", since I use "Go To Definition" whenever I'm not sure about where the exact method call or variable name comes from.
 

hanser

Ars Legatus Legionis
43,855
Subscriptor++
Thanks again. I'll just leave it in its current location, and I might do the MiscClasses thing, too, at some point. I've got at least two more to create, and it'd get a bit silly to just leave them in the same source file.

--

In terms of the code you wrote, I'm not seeing the Dispose() method called at all. When a user closes a window, is this memory being released automatically?
 

Seltsam

Ars Tribunus Militum
2,881
hanser":1i4p8bwl said:
In terms of the code you wrote, I'm not seeing the Dispose() method called at all. When a user closes a window, is this memory being released automatically?

I'd change the FormClosed handler to this:

Code:
static void newFrm_FormClosed(object sender, FormClosedEventArgs e)
{
	FormCount--;  // this isn't thread-safe
	Form closingForm = sender as Form;
	if (closingForm != null)
	{
		closingForm.FormClosed -= newFrm_FormClosed;
		closingForm.Dispose();
	}
	if (FormCount == 0) // this isn't thread-safe
	{
		Application.ExitThread();
	}
}
 

hanser

Ars Legatus Legionis
43,855
Subscriptor++
Seltsam":3cfyy99k said:
hanser":3cfyy99k said:
In terms of the code you wrote, I'm not seeing the Dispose() method called at all. When a user closes a window, is this memory being released automatically?

I'd change the FormClosed handler to this:

Code:
static void newFrm_FormClosed(object sender, FormClosedEventArgs e)
{
	FormCount--;  // this isn't thread-safe
	Form closingForm = sender as Form;
	if (closingForm != null)
	{
		closingForm.FormClosed -= newFrm_FormClosed;
		closingForm.Dispose();
	}
	if (FormCount == 0) // this isn't thread-safe
	{
		Application.ExitThread();
	}
}
So this is the first multi-threaded app I've ever written, if you could call it that. (I'm using BackgroundWorker to do some stuff in the background: write to a temp file in the event of a crash, and stick an object into a list so I can have robust "undo" functionality.) I know very little about thread safety, except what I've just read on Wikipedia. Based on some of the stuff that should trigger alarm(s), I could probably do a better job of rewriting the background thread.

That being said, I'm not sure how you know that the above code isn't thread safe? This is due to my undoubtedly incomplete understanding of the concepts used in multi-threaded apps. Can you elaborate on how you know, and maybe how you'd fix it? (Does it even need to fixed from a practical PoV?)
 
Seltsam":1z894rq2 said:
It's only thread safe if you close all forms from the same thread.
That's the only way it can happen. You can't close a form from any thread but the UI thread. All form events happen on the UI thread.

If BackgroundWorkers can close forms from their worker thread, then you have a problem.

They can't. You'll get an InvalidOperationException thrown. If you do it from the ProgressChanged event handler of a BackgroundWorker, that event handler gets marshalled to the UI thread.
 
hanser":6g10ms8p said:
Thanks again. I'll just leave it in its current location, and I might do the MiscClasses thing, too, at some point. I've got at least two more to create, and it'd get a bit silly to just leave them in the same source file.

--

In terms of the code you wrote, I'm not seeing the Dispose() method called at all. When a user closes a window, is this memory being released automatically?

Yep. I exercised this functionality in a loop, and to be really sure, I added a 1MB byte[] array that's allocated during the form constructor. After 4000 form create/closes, there was 0 memory leaked.
 

Seltsam

Ars Tribunus Militum
2,881
El Guapo":158i77vx said:
Seltsam":158i77vx said:
It's only thread safe if you close all forms from the same thread.
That's the only way it can happen. You can't close a form from any thread but the UI thread. All form events happen on the UI thread.

If BackgroundWorkers can close forms from their worker thread, then you have a problem.

They can't. You'll get an InvalidOperationException thrown. If you do it from the ProgressChanged event handler of a BackgroundWorker, that event handler gets marshalled to the UI thread.

I understand all that, I just didn't make any assumptions that the forms are being created correctly.
 
Seltsam":v6sukdc6 said:
El Guapo":v6sukdc6 said:
Seltsam":v6sukdc6 said:
It's only thread safe if you close all forms from the same thread.
That's the only way it can happen. You can't close a form from any thread but the UI thread. All form events happen on the UI thread.

If BackgroundWorkers can close forms from their worker thread, then you have a problem.

They can't. You'll get an InvalidOperationException thrown. If you do it from the ProgressChanged event handler of a BackgroundWorker, that event handler gets marshalled to the UI thread.

I understand all that, I just didn't make any assumptions that the forms are being created correctly.

That would certianly lead to a host of other problems.

At any rate, hanser, in the general case, globals (like FormCount) should be protected when they can be accessed via multiple threads:

Code:
    class AppCtx : ApplicationContext
    {
        public AppCtx()
            : base()
        {
            CreateNewForm();
        }

        private static Object FormCountLock = new Object();
        private static int FormCount = 0;

        public static void CreateNewForm()
        {
            lock (FormCountLock)
            {
                Form1 newFrm = new Form1();
                newFrm.FormClosed += new FormClosedEventHandler(newFrm_FormClosed);
                newFrm.Show();
                FormCount++;
            }
        }

        static void newFrm_FormClosed(object sender, FormClosedEventArgs e)
        {
            lock (FormCountLock)
            {
                FormCount--;
            }

            lock (FormCountLock)
            {
                if (FormCount == 0)
                {
                    Application.ExitThread();
                }
            }
        }

    }

There's always more you can do, like try/catch around the form creation to notify the user if it cannot be created properly, etc. This was always meant to be the basic framework for accomplishing what you were after.
 

hanser

Ars Legatus Legionis
43,855
Subscriptor++
El Guapo":3ujn3cmy said:
Seltsam":3ujn3cmy said:
I understand all that, I just didn't make any assumptions that the forms are being created correctly.
That would certianly lead to a host of other problems.
That sounds like it'd be an issue with .NET, then. I'm not really doing anything fancy with form creation. :)

At any rate, hanser, in the general case, globals (like FormCount) should be protected when they can be accessed via multiple threads:
Yeah I've been reading the PDF book Seltsam mentioned, and playing with some of the code examples (before I got distracted by anonymous functions at any rate @_@), and saw the locking syntax you used.

My multithreading consists of a BackgroundWorker thread, nothing more. It accesses the contents of a TextBox (read-only) every three seconds, getting the content of the TextBox, writing the text to a temporary file (in the event of an application crash), and recording the contents and cursor position in a List of a simple object I haven't created yet.

This is the DoWork function from my BackgroundWorker:

Code:
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
    BackgroundWorker bw = sender as BackgroundWorker;
    string lastWritten = null;

    while (true)
    {
        if (bw.CancellationPending == true)
        {
            e.Cancel = true;
            break;
        }
        else
        {
            if (lastWritten == txtText.Text)
            {
                Thread.Sleep(1000);
            }
            else
            {
                writeFile(tempFileName);
                lastWritten = txtText.Text;
                Thread.Sleep(3000);
            }
        }
    }
}

In my OnFormClosing() function, I send a bw.CancelASync(), otherwise the app crashes messily.

--

Edit: There are some holes in my logic, and badly-implemented ideas. For example, when the person is typing, what's written to the temp file may not be the contents of the TextBox. It could be a character or so off. I've been thinking about rewriting writeFile() to be more generic eg writeFile(string filename, string contents) instead of relying on a global variable.

On an unrelated note: GUI stuff is REALLY tedious.
 

Seltsam

Ars Tribunus Militum
2,881
For example, when the person is typing, what's written to the temp file may not be the contents of the TextBox. It could be a character or so off.

The following should solve this (I don't know how else you could mutate txtText).

I'd still improve this with SpinWait instead of Thread.Sleep if you can target .NET 4.
Code:
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
	BackgroundWorker bw = sender as BackgroundWorker;
	String lastWritten = null;

	for (;;)
	{
		if (bw.CancellationPending)
		{
			e.Cancel = true;
			return;
		}
		
		String currentText = txtText.Text;
		
		if (String.Equals(lastWritten, currentText, StringComparison.CurrentCulture))
		{
			Thread.Sleep(1000);
			continue;
		}

		writeFile(tempFileName, currentText);
		lastWritten = currentText;
		Thread.Sleep(3000);
	}	
}
 

ShuggyCoUk

Ars Legatus Legionis
10,388
Subscriptor++
he's sleeping for *seconds*.
Why on earth would SpinWait a good idea?

Tip for anyone thinking of using SpinWait -> most people shouldn't. It implies you are operating on levels where the OS thread scheduling quantums matter, and if you're doing that you should use someone else's library or start learning about some fairly esoteric stuff.
 

DavlinLotze

Ars Scholae Palatinae
830
hanser":14rmf8dx said:
It accesses the contents of a TextBox (read-only) every three seconds, getting the content of the TextBox, writing the text to a temporary file...
I'm a little confused. If it's read-only, why are you having to save its contents every 3 seconds?

Might it be better to use events to trigger saving stuff? Why should the save event be triggered every 3 seconds even if the application is sitting idle? Handling a TextChanged event will be more often when actual typing is going on, but it won't get triggered the rest of the time. You wouldn't have to save every time the TextChanged is triggered - just handle it. If you stick with the 3-second triggering, you could at least turn it on when the TextBox GotFocus and save and turn it off when it LostFocus.

hanser":14rmf8dx said:
On an unrelated note: GUI stuff is REALLY tedious.
Yes, it is.
 

Seltsam

Ars Tribunus Militum
2,881
ShuggyCoUk":n1g8vgl9 said:
he's sleeping for *seconds*.
Why on earth would SpinWait a good idea?

Tip for anyone thinking of using SpinWait -> most people shouldn't. It implies you are operating on levels where the OS thread scheduling quantums matter, and if you're doing that you should use someone else's library or start learning about some fairly esoteric stuff.

Sleeping for seconds is not a good idea either. Might as well use a Timer.
 

hanser

Ars Legatus Legionis
43,855
Subscriptor++
DavlinLotze":2ml44kpl said:
hanser":2ml44kpl said:
It accesses the contents of a TextBox (read-only) every three seconds, getting the content of the TextBox, writing the text to a temporary file...
I'm a little confused. If it's read-only, why are you having to save its contents every 3 seconds?
Because "accesses" was vague. It reads the contents of the TextBox every 3 seconds. The contents can change as a user types; the TextBox itself is not read-only. :)

Might it be better to use events to trigger saving stuff? Why should the save event be triggered every 3 seconds even if the application is sitting idle? Handling a TextChanged event will be more often when actual typing is going on, but it won't get triggered the rest of the time. You wouldn't have to save every time the TextChanged is triggered - just handle it. If you stick with the 3-second triggering, you could at least turn it on when the TextBox GotFocus and save and turn it off when it LostFocus.
Think Notepad. It's a TextBox, and nothing but.

I'm already using TextChanged to handle some other real-time stuff, and I'd rather separate the GUI from the business logic as much as possible. In any case, I'm going to be using the same thread to be implementing the undo functionality anyway. Having character-by-character undo isn't especially useful. I think 3 second time increments make more sense if the contents have changed.
 

hanser

Ars Legatus Legionis
43,855
Subscriptor++
ShuggyCoUk":1q2lxsjh said:
he's sleeping for *seconds*.
Why on earth would SpinWait a good idea?

Tip for anyone thinking of using SpinWait -> most people shouldn't. It implies you are operating on levels where the OS thread scheduling quantums matter, and if you're doing that you should use someone else's library or start learning about some fairly esoteric stuff.
I did some reading yesterday morning on SpinWait, and was going to post the same thing. I'm sleeping for seconds so why would SpinWait be a good idea? There's even some indication that it's gone in Windows 7. The case becomes weaker when I change the first Sleep call to 3000, like the other. (I was pulling times out of my butt.)
 

ShuggyCoUk

Ars Legatus Legionis
10,388
Subscriptor++
There's even some indication that it's gone in Windows 7.

That is referring to the spin lock done by the dispater infrastruture within the OS scheduler. Spin waits in general remain (they are quite simply a library call that should do the most efficient 'donothing' operation on your target platform with soem degree of predictable 'duration' for some metric of duration).
On recent x86 cpus this will be HALT instructions which allows the core to reduce power as well as allowing HyperThreading to kick in and make use of the core's execution pipeline while you're twiddling your metaphorical thumbs.
 

hanser

Ars Legatus Legionis
43,855
Subscriptor++
OK, so I've finished building a new piece of functionality. It's a form that checks the temp file directory to see if there are any temp files that need to be recovered, in the event that the last program termination was abnormal. This form should be loaded before the main form, which, I suspect, means altering the application context again?

Program.cs:
Code:
static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new AppCtx());
        }

ApplicationContext class:
Code:
class AppCtx : ApplicationContext
	{
		public AppCtx()
			: base()
		{
			CreateNewForm();
		}

		private static int FormCount = 0;

		public static void CreateNewForm()
		{
			frmMain newFrm = new frmMain();
			newFrm.FormClosed += new FormClosedEventHandler(newFrm_FormClosed);
			newFrm.Show();
			FormCount++;
		}

		static void newFrm_FormClosed(object sender, FormClosedEventArgs e)
		{
			FormCount--;
			if (FormCount == 0)
			{
				Application.ExitThread();
			}
		}
	}

It seems like maybe I could stick it before frmMain newFrm = new frmMain(). The problem is that hitting Ctrl+N triggers CreateNewForm(), and I only want the recovery dialog to happen when the program is starting up, not every time a new document window is spawned.
 
Status
Not open for further replies.