Zoom in using two forms

There are several forms in my project. Form1 contains a pictureBox that displays jpeg. In Form2, I have a trackBar that I would like to control the zoom level of the image in Form1. To keep it simple, I only need 2 or 3 zoom levels. I set the pictureBox to view in the Designer view. However, when I try to reference the pictureBox in Form2, it says that it does not exist. Below is the code I use to call Form2 in Form1

Form2 dataWindow = new Form2(); dataWindow.ShowDialog(); 

In short, I need two things:

1) Change the properties of pictureBox1 from a separate form. 2) Create a simple scaling formula.

+4
source share
2 answers

1) Pass the link of form1 to the constructor of form2:

 Form2 dataWindow = new Form2(this); dataWindow.Show(); 

...

 private form1 as Form1; public Form2(Form1 frm1) { form1 = frm1; } 

Then in Form2s, TrackBar_Scroll refers to the PictureBox events through the private member form1 variable: form1.PictureBox1.Property

2) Enlarge your shots with PictureBox to zoom with the mouse wheel


The best way is events:

 public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { var form2 = new Form2(); form2.TrackBarMoved += new Action<int>(ZoomPictureBox); form2.ShowDialog(); form2.TrackBarMoved -= new Action<int>(ZoomPictureBox); } private void ZoomPictureBox(int zoomFactor) { pictureBox1.Width = 100 * zoomFactor; pictureBox1.Height = 100 * zoomFactor; } } public partial class Form2 : Form { public Form2() { InitializeComponent(); } public event Action<int> TrackBarMoved; private void trackBar1_Scroll(object sender, EventArgs e) { TrackBarMoved(trackBar1.Value); } } 
+2
source

He believed that poor design allowed other classes to modify the internal form controls. The form should be responsible for all components. You should never post any internal controls. He also considered it bad practice for a child form to have a link to the parent form.

An appropriate way to approach this problem is through events. The detailed form Form2 should define a public event:

 public event Action<int> TrackBarMoved; 

Form2 can trigger this event when moving the track and pass the position of the track panel as a parameter (if it makes sense to transfer something else, for example, the zoom level or something else you want, this is also good).

Form1 can subscribe to this event when creating From2 and change the image scale (internally, from within Form1 ) depending on the position of the track panel.

+3
source

Source: https://habr.com/ru/post/1448050/


All Articles