this.richTextBox1_VScroll);
this.richTextBox2.VScroll += new System.EventHandler(this.richTextBox1_VScroll);

[DllImport("user32.dll")]
static extern int SendMessage(IntPtr hWnd, UInt32 Msg, Int32 wParam, Int32 lParam);
const int EM_GETFIRSTVISIBLELINE = 0x00CE;
const int EM_LINESCROLL = 0x00B6;
private void richTextBox1_VScroll(object sender, EventArgs e)
{
  int linenum1 = SendMessage(this.richTextBox1.Handle, EM_GETFIRSTVISIBLELINE, 0, 0);

  int linenum2 = SendMessage(this.richTextBox2.Handle, EM_GETFIRSTVISIBLELINE, 0, 0);

  int lines = linenum1 - linenum2;
  IntPtr Hrtb = this.richTextBox2.Handle;
  if(this.richTextBox2.Focused)
  {
    lines = - lines;
    Hrtb = this.richTextBox1.Handle;
  }

  SendMessage(Hrtb, EM_LINESCROLL, 0, lines);
}

You will need to know some p/invoke knowledge:

http://msdn.microsoft.com/en-us/magazine/cc164123.aspx

SendMessage Function

http://msdn.microsoft.com/en-us/library/ms644950(VS.85).aspx

EM_GETFIRSTVISIBLELINE Message

http://msdn.microsoft.com/en-us/library/bb761574(VS.85).aspx

EM_LINESCROLL Message

http://msdn.microsoft.com/en-us/library/bb761615(v=VS.85).aspx

 

此idea来自处理一个客户的windows Form的项目需求,有兴趣的朋友可阅读下需求:

http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/fafa0d7d-fbd4-42ac-8cde-2d434ef567ab

 

p/invoke SendMessage to Control scroll bar, and implement a simple compare windows with RichTextBox

PS:我的同事开发了一个MSDN论坛的小工具,有兴趣的朋友可以试试,此工具已开始在国内推行:

p/invoke SendMessage to Control scroll bar, and implement a simple compare windows with RichTextBox

相关文章: