Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display image in pop-up window from c# class library

I need to display a Bitmap image in a pop-up window created by a c# class library. How is this possible?

I have tried the following:

        Bitmap img = tpv.Img();
        Graphics graphics = Graphics.FromImage(img);
        graphics.DrawImage(img, 0, 0);

and

        Bitmap img = tpv.Img();
        PictureBox pb = new PictureBox();
        pb.Size = img.Size;
        pb.Image = img;
        pb.Show();

however a window is not showing. Is it possible to get a class library to create a pop-up window displaying a bitmap image?

like image 701
Casper Thule Hansen Avatar asked Apr 16 '12 13:04

Casper Thule Hansen


Video Answer


1 Answers

Assuming WinForms, you need to add the PictureBox to a top-level Window like a Form. If you're using WPF the concept is identical, except that you would add your picture box to a Grid or something before showing the Window.

using (Form form = new Form()) {
    Bitmap img = tpv.Img();

    form.StartPosition = FormStartPosition.CenterScreen;
    form.Size = img.Size;

    PictureBox pb = new PictureBox();
    pb.Dock = DockStyle.Fill;
    pb.Image = img;

    form.Controls.Add(pb);
    form.ShowDialog();
}

Note that in my example it will show the form as modal. If you need a non-modal form call form.Show() instead and remove the using block so your form is not disposed immediately.

However, better design pattern would be to design your class library method to return the image to your UI, and have your main UI show the image instead. A framework API should never show a UI directly like this.

like image 72
David Anderson Avatar answered Sep 27 '22 18:09

David Anderson