两个gridcontrol 的滚动位置一致
时间: 2023-09-18 07:09:21 浏览: 79
要使两个GridControl的滚动位置一致,可以使用GridControl的Scroll事件和SetScrollInfo函数。具体实现步骤如下:
1. 在两个GridControl的Scroll事件中,获取滚动条的位置信息:
```
private void gridControl1_Scroll(object sender, ScrollEventArgs e)
{
int scrollPos = GetScrollPos(gridControl1.Handle, SB_VERT);
SetScrollPos(gridControl2.Handle, SB_VERT, scrollPos, true);
SendMessage(gridControl2.Handle, WM_VSCROLL, (IntPtr)SB_THUMBPOSITION + 0x10000 * scrollPos, IntPtr.Zero);
}
private void gridControl2_Scroll(object sender, ScrollEventArgs e)
{
int scrollPos = GetScrollPos(gridControl2.Handle, SB_VERT);
SetScrollPos(gridControl1.Handle, SB_VERT, scrollPos, true);
SendMessage(gridControl1.Handle, WM_VSCROLL, (IntPtr)SB_THUMBPOSITION + 0x10000 * scrollPos, IntPtr.Zero);
}
```
2. 在窗体Load事件中,注册滚动条信息:
```
private void Form1_Load(object sender, EventArgs e)
{
SetScrollRange(gridControl1.Handle, SB_VERT, 0, 100, true);
SetScrollRange(gridControl2.Handle, SB_VERT, 0, 100, true);
}
```
3. 在窗体关闭前,注销滚动条信息:
```
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
SetScrollRange(gridControl1.Handle, SB_VERT, 0, 0, true);
SetScrollRange(gridControl2.Handle, SB_VERT, 0, 0, true);
}
```
其中,GetScrollPos、SetScrollPos、SetScrollRange和SendMessage是Win32 API函数,定义如下:
```
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern int GetScrollPos(IntPtr hWnd, int nBar);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern int SetScrollPos(IntPtr hWnd, int nBar, int nPos, bool bRedraw);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern int SetScrollRange(IntPtr hWnd, int nBar, int nMinPos, int nMaxPos, bool bRedraw);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern int SendMessage(IntPtr hWnd, int wMsg, IntPtr wParam, IntPtr lParam);
```
其中,nBar参数表示滚动条类型,可以是SB_HORZ(水平滚动条)或SB_VERT(垂直滚动条);nPos参数表示滚动条的位置;nMinPos和nMaxPos参数表示滚动条的最小值和最大值;bRedraw参数表示是否重绘滚动条。wMsg参数表示消息类型,可以是WM_VSCROLL(垂直滚动条消息)或WM_HSCROLL(水平滚动条消息);wParam和lParam参数表示消息参数,具体取决于消息类型。
阅读全文