Issue with OpenFileDialog and threading - vb.net

I just upgraded from VS 2005 to VS 2012. This is a new issue that I do not understand. I am using the default "Form1" class the VS automatically creates. I added a button to open a file open dialog and when I click the button I get this error:
Current thread must be set to single thread apartment (STA) mode before OLE calls can be >made. Ensure that your Main function has STAThreadAttribute marked on it. This exception >is only raised if a debugger is attached to the process.
I have added " to Public Class Form1:
<STAThread()> Public Class Form1
But I get this...
Attribute 'STAThreadAttribute' cannot be applied to 'Form1' because the attribute is not >valid on this declaration type.
I have searched but get some info telling me that I need to set the entry point (Form1 I believe) to be Single Thread Attribute but the above code does not work.
How?

The <STAThread()> attribute cannot be added to classes like your form. It only works when it is applied to the Main function, which is the entry point of your application.
But VB.NET hides this function from you because it is rare that one needs to mess with Main in a WinForms application. It is just needed to get the plumbing set up for your app, which the compiler can manage for you. This is controlled by the "Application Framework" checkbox in the project options. If this is checked, the compiler automatically generates the Main function and the required plumbing. You can disable this option, but it makes life quite a bit harder for the average WinForms developer because you'll have to write and maintain your own Main function.
The real question here is why this is a problem at all. The compiler-generated Main function for a WinForms application is always going to have the STAThread attribute applied to it. That is just how the WinForms framework is designed to run. If that is not happening, then there is something badly wrong with your project. I would recommend scrapping it and starting over letting Visual Studio create a new WinForms project from one of the built-in templates. Everything should Just Work™.
The other option, of course, is that you're trying to display the OpenFileDialog on a separate thread (other than your main UI thread). But from your description in the question (adding a button to the form to display the dialog), it doesn't sound like this is the case. Regardless, the solution is not to do that. For example, if you're using a BackgroundWorker to do work on a non-UI thread in order to keep the UI responsive, that's great, but you'll want to do all of the UI stuff like showing an OpenFileDialog on the main UI thread before invoking the BackgroundWorker. There is a way to set a particular thread's apartment state using the SetApartmentState function, but I really don't recommend showing an OpenFileDialog on a background thread.

Related

undo for non textbox controls

new to .net coming from vba decided to rewrite a management app using vb.net and SQL Server.
Started writing the base library for my application.
I created custom controls to use in my application that would expose a Zoom function, background color for the current active control a .modified property similar to the one available in textbox and some extra other properties (SQLTableName, SQLColumnName, ...) to enable iterating through a container (form) for modified controls and Update/Insert into a SQL table via a SQLProcessClass.
Concurrently I'd like to also implement a simple undo functionality.
My first idea was to add a PrevValue variable set in the OnEnter event if the Modified property is False, exposing an OldValue property and an Undo method in the custom controls.
However I found that the TextBoxBaseClass already exposes an Undo method and that there is an UndoEngineClass available.
Unfortunately the vs helpfile does not give examples of how to use / implement that class.
Could someone explain the usage of the UndoEngine class non-textbox controls and if it is advisable to use it or rather write my own (as I first intended to do - I also found some interesting articles about undo/redo classes) but why reinvent the wheel in case .net already provides a class for it.
thks

Dispose unmanaged resources created in Windows Form

When an object is created in the .Designer.vb file from the Windows Form Designer, is a Dispose() call generated automatically for each object or must this be done manually?
Specifically, I have an object that uses unmanaged resources (by calling ShowDialog(), requiring a call to Dispose()) that is created in the Windows Form Designer. Do I still need to call Dispose() on that object?
Note: It is advised not to call Dispose() more than once on the same object.
While I dont know the answer, let me tell you how you can get the answer and learn a neat trick for designing components for winforms (might work for others but haven't tried).
Assuming you have a project that already references your component, create a new project and set the "Start External Program" to "C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\devenv.exe" (change this based on your version of visual studio, this is from 2005)
Run this project, which will then run another instance of VS. You have now opened VS in debug mode. Now open your project you are using to build/test your component (from the second instance of VS), set a break-point and test it. You should be able to see it hit your break-point in the dispose code.
This is great for testing VS Add-ins and designer components.
This was one of those questions where the answer is "because that is the way it works", but then you realize you don't actually know how it is implemented. So I spent a few moments to dig up the details.
Anything that is a Control (button, textbox, whatever) that is added to the Controls collection is disposed for you automatically. This implementation is inherited all the way back from the Control class itself.
Anything that is a non-graphical Component (like a Timer for example) that is added to the auto-generated components object in the MyForm.Designer.vb file is also disposed for you. In this case, components object, while implementing the System.ComponentModel.IContainer interface, will be an instance of System.ComponentModel.Container that handles the actual Dispose.

VB.NET - Ctrl + Break suspends code on "Partial Class frmMain"

This is an IDE question for Visual Basic 2008 Express Edition. It might be a bug in the IDE, or maybe it's my fault somehow?
My main form is named frmMain and in my application's properties I have set frmMain as my startup object. All of that seems like what a lot of software engineers do.
But while debugging I hit Ctrl + Break, as I have done for years, and I get an behavior in the IDE that I wasn't expecting. Upon doing so, I get the green background text and the green arrow indicating in a tooltip:
This is the next statement to execute when this thread returns from the current function.
Even if I didn't have the designer document open, it automatically opens frmMain.Designer.vb in the editor and hihglights line in green. The line is of course: Partial Class frmMain which is line 2 of the file. (Yes, it's highlighting the second line of the designer-generated code.)
frmMain seems to have fully loaded and it's my startup object. As far as I know, there shouldn't be a "next statement to execute" at all because code should be idle. I don't want to see the Designer.vb document... I want to edit my own code.
What's causing this? Even though my form is behaving just fine, could there somehow be an unfinished aspect of loading the form such that it is "not returning" from a function?
The Visual Basic compiler will add an entry point in your form. The entry point is the standard main function or "shared sub main", which in turn contains the code "application.run(new form)". Since this is compiler generated code there is no source location, so the Visual Basic editor highlights the class definition.
The clue to this is in the call stack. Notice the Main().
Shared Sub Main()
Application.Run(new frmMain)
End Sub
I found the answer on my own:
I checked the "Enable application framework" checkbox in the solution's properties, and all is well!
I believe this issue arose when I was working on experimental code in which I had desired to make Sub Main my startup object. I had cleared the checkbox because doing so is necessary to use Sub Main.
When the experiment didn't pan out I reset the startup object back to frmMain, and my app worked fine. However I had not re-checked the box. I hadn't noticed the change in the IDE behavior for several days (when I needed the more standard behavior) so I had not observed any correlation.
Although checking that box is definitely the solution, it's still not exactly clear to me is what the heck this box actually does, other than cause me to spend a lot of time on StackOverflow.com! ;-)
To others who encounter a similar situation, I'm now quite confident that my settings were not corrupt, and if you're using the Express edition, please don't be mislead by MS documentation which may lead you to believe it's the "Just My Code" option. This option cannot be changed in the Express versions. (But it's not because you can't turn it on -- It's because you can't turn it OFF in Express!)
Thanks to everyone for your efforts.
I'm going to guess that it is trying to show you the equivalent of:
Application.Run(new frmMain)
This is the code that gets generated to startup your form. But in VB.NET this code gets burried. Create a Main() function and change your startup type to that with this line in it and repeat the process. You'll see it highlight Application.Run. That is the method that contains your Windows message pump loop.

How can I get my VB.NET forms application startup method to be Sub Main() in Program.vb?

Trying to get it to behave like C#, where there is a Program class with a static Main method.
However, in the project properties, I cannot set Program.vb to be the startup object, only the forms (it is a forms application).
Am I missing something?
I am using the VS2010 and the latest VB.
Uncheck Enable Application Framework in Project Properties.
You need to switch off “Application Framework” on the main page of the project settings.
The application framework provides its own entry point which sets up a few things that are subsequently used (e.g. application events, single instance checks etc.) and then just displays the main form using System.Windows.Forms.Application.Run. That’s why you can only supply the main form, not a custom entry point method.

Start VB.NET GUI app using Sub Main or form startup object?

Is there any reason to start a GUI program (application for Windows) written in VB.NET in the Sub Main of a module rather than directly in a form?
EDIT: The program won't take any command line parameters and it will be executed as a GUI program always.
The primary reason for using Main() in VB .NET 1.x was for adding code that needed to run before any forms were loaded. For example, you might want to detect whether an instance of your Windows Forms app was already loaded. Or you might want to intercept any unhandled exception for the AppDomain:
AddHandler AppDomain.CurrentDomain.UnhandledException, AddressOf MyExceptionFilter
But the next version of VB and Visual Studio 2005 introduced a new Application model that made Main() unnecessary in most scenarios. You can now intercept the My.Application.Startup event to add code that needs to run before any forms are loaded.
Note that the code for the Startup event handler is stored in the ApplicationEvents.vb file, which is hidden by default.
You can do it either way, but you should really only keep code in the form that is directly related to the operations and user interface elements on that form. Application startup code isn't related to UI, normally concerned with splash screens, checking network connectivity, verifying a single instance only, setting up user configuration settings, and so on.
After the above items (or the appropriate initialization code for your app) are complete, Sub Main can create an instance of the main form, then show it so the user can begin interacting with your application.
This separates startup code from your form code. Later, when you're maintaining the application, you'll be glad you separated the two.
Yes, and I have done it a few times.
One reason is, that if your app is COM EXE (speaking now from a VB6 point of view) then you want to be able to detect in what context the EXE is being called (being launched or being spoken to by some other app).
For example:
Sub Main()
If App.StartMode = vbSModeAutomation Then
...
Else
...
End If
End Sub
Another is if you want your app to be able to handle any command line parameters.
For example:
Sub Main()
If App.PrevInstance Then End
If InStr(Command, "/s") > 0 Then
Form1.Show
ElseIf InStr(Command, "/p") > 0 Then
LoadPicture ("c:\windows\Zapotec.bmp")
End If
End Sub
(from one of my attempts to make a screen saver)
No, if you always want to show that form.
Yes, if you sometimes want to use your app without GUI, just using command line.
Yes, if I want to display different forms depending on some parameter (in a file, on a remote server, etc.).