Click here to Skip to main content
15,848,904 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How to scroll the image in picture box inside the panel using arrow keys

I can scroll the images in picturebox using the below code on picturebox keydown event

if (e.KeyCode == Keys.Left)
pictureboxImage.Left = pictureboxImage.Left + 10;

it scrolls correctly but the problem is when we press arrow keys continuosly it flows outside the panel. Panel will be blank for sometimes because picturebox will be outside the panel.
but when we use mouse to scroll it works perfectly, I want same steps on arrow keypress event.

Please help me on this.

Updated 19-Apr-22 23:48pm

1 solution

Basically you need to check that you are not out of bounds of the picture box.

1. Add a Panel called panel1 to the Form.
2. Set the property form1.PreviewKey = true
3. Set the property panel1.AutoScroll = true
4. Set the property panel1.TabStop = true (in order to be able to set focus to the control)
5. Add the PictureBox inside the panel and call it pictureBox1
6. Set the property pictureBox1.SizeMode = AutoSize

Then add the code like this.
The step size is of course up to your own desire.
private void Form1_KeyDown(object sender, KeyEventArgs e)
    if (e.KeyCode == Keys.Right)
        if ((panel1.HorizontalScroll.Value + panel1.HorizontalScroll.SmallChange) >= panel1.HorizontalScroll.Maximum)
            panel1.HorizontalScroll.Value = panel1.HorizontalScroll.Maximum;
            panel1.HorizontalScroll.Value += panel1.HorizontalScroll.SmallChange;
    else if (e.KeyCode == Keys.Left)
        if ((panel1.HorizontalScroll.Value - panel1.HorizontalScroll.SmallChange) < panel1.HorizontalScroll.Minimum)
            panel1.HorizontalScroll.Value = panel1.HorizontalScroll.Minimum;
            panel1.HorizontalScroll.Value -= panel1.HorizontalScroll.SmallChange;
    // Add similar code for the up and down arrows

Maybe this CodeProject article can help you further.

Fast Image Scrolling in C#[^]
Share this answer
SukirtiShetty 3-Sep-14 2:17am    
thank you for your reply.
I have tried your solution, but it works same as before.
I added picturebox inside the panel. Please help me in this.
George Jonsson 3-Sep-14 3:55am    
I have updated the answer with an example.
SukirtiShetty 3-Sep-14 4:44am    
Thank You so much it worked perfectly.
George Jonsson 3-Sep-14 4:50am    
You are welcome.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900