Click here to Skip to main content
15,888,113 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hello,
I'm trying to add an image into PictureBox with OpenFileDialog() method.

What I have tried:

C++
private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) {
    OpenFileDialog^ ofd = gcnew OpenFileDialog;
    ofd->InitialDirectory = "C:\\";
    ofd->Filter =
        "Images (*.bmp;*.gif;*.jpg;*.jpeg;*.png)|"
        "*.bmp;*.gif;*.jpg;*.jpeg;*.png|"
        "Bitmaps (*.bmp)|*.bmp|"
        "GIFs (*.gif)|*.gif|"
        "JPEGs (*.jpg)|*.jpg;*.jpeg|"
        "PNGs (*.png)|*.png";
    ofd->FilterIndex = 1;
    if (ofd->ShowDialog() == System::Windows::Forms::DialogResult::OK) {
            pictureBox11->Image = Image::FromFile(ofd->FileName);
            pictureBox11->SizeMode = PictureBoxSizeMode::StretchImage;
        }
    else {
        MessageBox::Show("Can't open the file. Wrong file type", "ERROR", MessageBoxButtons::OK, MessageBoxIcon::Error) == System::Windows::Forms::DialogResult::No;
    }
    }

but when I click this button next message shows up:
'System.Threading.ThreadStateException: '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.'
Posted
Updated 13-Jun-18 7:23am

Since you haven't actually posted one, I will assume your question is what do you do about that message. The answer is given in the message.
Quote:
Ensure that your Main function has STAThreadAttribute marked on it
If that is not what you are after then you should consider actually asking a question.
 
Share this answer
 
When your read the documentation of STAThreadAttribute from Microsoft you would have read that:
"You're developing a Windows Forms app. Windows Forms apps must be single-threaded if they communicate with Windows system components such as the Clipboard or Windows common dialog boxes, or if they use system features such as drag-and-drop functionality"

What means that you need to set that in the project settings to use the Common File Dialog. Such problems are knowns as: "Works as designed"
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900