C# Scrolling a Panel in windows forms

自闭症网瘾萝莉.ら 提交于 2019-12-04 18:52:27

问题


I'm using VS2010, Windows 7

I have a panel with lots of picture-boxes. It has

AutoScroll = true

The scroll bars work properly when i drag it, or click on it. However, i want to scroll it with the wheel and arrow keys.

The wheels don't respond at all (and adding event handlers to the form doesn't work, as it ceases firing when i change focus), and to use the arrow keys i'd have to programatically scroll. I tried the following:

panel3.VerticalScroll.Value = panel3.VerticalScroll.Maximum;

This doesn't work, the scrollbar barely moves at all. Maximum is always 100 for some reason.

What i tried on the wheel problem (doesn't work):

// Fires as long as i don't change focus to anything
this.MouseWheel += new MouseEventHandler(Panel1_MouseWheel);

private void Panel1_MouseWheel(object sender, MouseEventArgs e)
{
    panel3.Focus();
}

Thank you.


回答1:


A couple things to try:

Make your Panel have the first TabIndex property. That is:

panel1.TabIndex = 0;

Obviously, the other controls on the form should be re-indexed properly.

Also, try adding the focus in the MouseDown event:

void panel1_MouseDown(object sender, MouseEventArgs e) {
  if (!panel1.Focused)
    panel1.Focus();
}

You could do MouseEnter, too, but that might be an odd user interface since moving the mouse over the panel would steal focus away from the current active control.

You shouldn't need to subscribe to the MouseWheel event. It should move the scrollbar automatically.




回答2:


You scroll a Panel by assigning the AutoScrollPosition property. Beware that it uses negative values.

The reason the mouse wheel doesn't work is because neither the panel nor the picture boxes are focusable controls. You'll need to rework the panel control a bit to make it a focusable. You'll find the code in this answer.




回答3:


Try

private void panel1_MouseEnter(object sender, EventArgs e)    
{    
   panel1.Focus();    
}


来源:https://stackoverflow.com/questions/8624737/c-sharp-scrolling-a-panel-in-windows-forms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!