Display image in pop-up window from c# class library
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.
Casper Thule Hansen
Updated on June 08, 2022Comments
-
Casper Thule Hansen almost 2 years
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?
-
Casper Thule Hansen about 12 yearsPerfect thank you. It is a test framework without any kind of GUI, so this is just a "debug" / random check option.
-
causa prima about 4 yearsThis does not work correctly! It should be form.ClientSize = img.Size; The code as written chops off the bottom of the image.