C ++ - 将图像从表单保存到文件

时间:2016-02-18 15:13:23

标签: winforms visual-c++ c++-cli

我是Windows Form Application编程的新手。我想捕获我的Windows窗体(使用CaptureScreen()函数)并通过使用SaveFileDialog单击按钮将其保存到文件中。这是我的代码:

private: System::Void CaptureScreen() 
{
    Drawing::Graphics^ myGraphics = this->CreateGraphics();
    memoryImage = gcnew Drawing::Bitmap(Size.Width, Size.Height, myGraphics);
    Drawing::Graphics^ memoryGraphics = Drawing::Graphics::FromImage(memoryImage);
    memoryGraphics->CopyFromScreen(this->Location.X, this->Location.Y, 0, 0, this->Size);
}

private: System::Void btnSave_Click(System::Object^  sender, System::EventArgs^  e) 
{
    SaveFileDialog^ saveDiag2 = gcnew SaveFileDialog();
    saveDiag2->Filter = "Dateityp PNG (*.PNG)|*.PNG|All files (*.*)|*.*";
    saveDiag2->FilterIndex = 1;
    saveDiag2->RestoreDirectory = true;
    if (saveDiag2->ShowDialog() == System::Windows::Forms::DialogResult::OK)
    {
        String^ savePath = saveDiag2->FileName;
        if (saveDiag2->OpenFile() != nullptr)
        {
            try
            { 
                CaptureScreen();
                if (memoryImage != nullptr)
                {
                    memoryImage->Save(savePath, Imaging::ImageFormat::Png);
                }
            }
            catch (Exception^)
            {
                MessageBox::Show("There was a problem saving the file."
                    "Check the file permissions.");
            }
        }
    }
}

我总是显示Exception。我做错了什么?

1 个答案:

答案 0 :(得分:0)

汉斯帕斯特是对的。你应该处理IDisposible对象。在C ++ CLI中,您可以借助msclr :: auto_handle智能指针来完成它。

<span id="ID" hidden>Enter you text here</span>

您还可以从Exception对象中检索有用的信息:

$("#ID").show();