Application of form. autoscrollposition in. net
Author: Yuan Xiaohui
Today, I wrote a winform program that supports scrolling. It mainly uses form autoscroll. The code is very simple. The key code is as follows:
/// <Summary>
/// Form load event
/// </Summary>
/// <Param name = "sender"> </param>
/// <Param name = "E"> </param>
Private void form1_load (Object sender, system. eventargs E)
{
// This is critical. Only when the property is true will the window be out of the window range when the control
// Automatically add a scroll bar and automatically scroll the control when we operate the scroll bar
This. autoscroll
= True;
}
/// <Summary>
/// Set an image file to picturebox1
/// </Summary>
/// <Param name = "FILENAME"> image file name </param>
Private void setimage (string filename)
{
Bitmap Bm = new
Bitmap (filename );
Picturebox1.backgroundimage = bm;
Graphicsunit bmgu = graphicsunit. pixel;
Rectanglef rectf = BM. getbounds (ref bmgu );
// Set the picturebox1 size and position. If the control is out of the form range, the form will automatically
// Add a scroll bar
Picturebox1.setbounds (0, 0, (INT) rectf. Width, (INT) rectf. Height );
}
/// <Summary>
/// Picturebox1 dobuleclick event
/// </Summary>
/// <Param name = "sender"> </param>
/// <Param name = "E"> </param>
Private void
Picturebox#doubleclick (Object sender,
System. eventargs E)
{
// Open a file dialog box and select an image file
Openfiledialog = new openfiledialog ();
Openfiledialog. Filter = "Image
Files | *. BMP; * .jpg).jpeg; *. GIF ";
If (openfiledialog. showdialog ()
= Dialogresult. OK)
{
// Set the image to be displayed
Setimage (openfiledialog. filename );
}
}
Run it. It seems to be normal. Double-click picturebox1 to open an image file. If the image size is too large, the scroll bar will automatically appear. There is only one case. First open a large image, drag the scroll bar to the end, and then open an image. The position shown in the image is incorrect (not in the upper left corner ). It's strange that I set X Y of picturebox1 to 0: picturebox1.setbounds (0,
0 ,......) It's really confusing !!
After studying the framework help file, I finally figured out the cause. Now I want to share with you: when we changed the position of the window scroll bar, the coordinate origin of the window client area changed, you can use form to offset the original coordinate point. autoscrollposition.
Now that the problem is found, the solution is simple. The last code for modifying the setimage function is:
Picturebox1.setbounds (autoscrollposition. X,
Autoscrollposition. Y, (INT) rectf. Width, (INT) rectf. Height );
Everything is OK !!