简体   繁体   中英

How do I ensure visibility of a control in a UserControl that has to be scrolled?

I have an UserControl(I use WinForms) with many components in it and you have to scroll up/down or left/right if you want to see a certain one. I now want to implement a searchbox which will allow you to search a component and when you select it in the results (a datagridview), the UserControl will scroll to make sure you can see the selected component.

My first idea was to check if the component location is bigger than the ClientSize, something like:

if (ivrMenu.X > _designerControl.ClientSize.Width && ivrMenu.Y > _designerControl.ClientSize.Height)
    MessageBox.Show("Down-Right");
else if (ivrMenu.X > _designerControl.ClientSize.Width)
    MessageBox.Show("Right");
else if (ivrMenu.Y > _designerControl.ClientSize.Height)
    MessageBox.Show("Down");

Obviously, this would work only if the scrolling position would be 0 for both H and V. So, I have to take into account the position of the current Scrolling Position or I could scroll to position 0 and then make my scrolling to the component but that wouldn't look so good.

My question is, how do I take into account the scrolling? How do I calculate the location of the visible area with the scrolling Position?

There are a couple of things you can try with a datagridview :

1) theGridView.FirstDisplayedScrollingRowIndex = theGridView.SelectedRows[0].Index;

2) theGridView.CurrentCell = theGridView.Rows[index].Cells[0];

The second will scroll to the item without moving it to the top of the view.

I did some math with the ClientSize, AutoScrollPosition and the Size of my components and this code seems to work perfectly:

if (ivrMenu.X + ivrMenu.Width < _designerControl.AutoScrollPosition.X * (-1))
    MessageBox.Show("Left");

if (ivrMenu.X + ivrMenu.Width > _designerControl.ClientSize.Width - _designerControl.AutoScrollPosition.X)
    MessageBox.Show("Right");

if (ivrMenu.Y + ivrMenu.Height < _designerControl.AutoScrollPosition.Y * (-1))
    MessageBox.Show("Up");

if (ivrMenu.Y + ivrMenu.Height > _designerControl.ClientSize.Height - _designerControl.AutoScrollPosition.Y)
    MessageBox.Show("Down");

this where is the position of the component (in my case ivrMenu) outside the visibe ClientArea. From this I just have to do the scrolling so the component fits the screen.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM