Monday, May 16, 2011

C# Notes

I made a stupid C# mistake today. In the constructor of my form, I had an OpenFileDialog.Show() call (to get the name of a file to operate on.) When I ran the program, the OpenFileDialog would show as expected. But after I pressed okay, the main application would not be the focused window.

It took me too long to figure out that since I was calling OpenFileDialog in the constructor, the Application wasn't initialized yet and so the OpenFileDialog.ShowDialog() was using another window as its parent. Using the call OpenFileDialog.ShowDialog(this), where this is the current form, made everything work as expected.

Another problem I had was not being able to exit the program by calling Application.Exit() in the constructor. Apparently, the Application isn't initialized before the constructor returns. So I'd either have to throw an exception for whoever is calling Application.Run() or else use the Environment.Exit(). I went with Environment.Exit()... not sure if there's any reason not to.

I spent a long time trying to figure out why I couldn't set an item as selected for a ListView by setting the Select property to true. Apparently, you're supposed to call ListView's Select method. I should look into this more.

More:

Use the Shown Callback in forms if you want to do stuff to controls outside of the contstructor but before things really start running. In the constructor, there are no event handlers and you can't exit the application without using Environment.Exit.

If you want to use a checkbox in a list view, that is built in. If you're listening for items checked, make sure you don't add the ListViewItem to the list until the checked value is correctly set.

When I first started .Net development, I couldn't get the KeyDownEvent listener to work for my form. It turns out I forgot to change the form's KeyPreviewProperty to true.

No comments: