如何获得.NET TrackBar跟踪器的位置?

时间:2010-04-26 13:29:16

标签: c# .net

我正在使用C#构建Windows窗体应用程序,并在我的表单上有TrackBar。如何计算跟踪器尖端的(像素)位置?我想从那里画一条线到我表格上的另一点。 另外,我还想计算尖端的最低和最高x位置。

1 个答案:

答案 0 :(得分:6)

由TrackBar包装的本机Windows控件有一个尴尬的限制,你无法获得第一个和最后一个tic标记的位置。但是,您可以获得通道和滑块的显示矩形。这个类返回它们:

using System;
using System.Windows.Forms;
using System.Drawing;
using System.Runtime.InteropServices;

class MyTrackBar : TrackBar {
  public Rectangle Slider {
    get {
      RECT rc = new RECT();
      SendMessageRect(this.Handle, TBM_GETTHUMBRECT, IntPtr.Zero, ref rc);
      return new Rectangle(rc.left, rc.top, rc.right - rc.left, rc.bottom - rc.top);
    }
  }
  public Rectangle Channel {
    get {
      RECT rc = new RECT();
      SendMessageRect(this.Handle, TBM_GETCHANNELRECT, IntPtr.Zero, ref rc);
      return new Rectangle(rc.left, rc.top, rc.right - rc.left, rc.bottom - rc.top);
    }
  }
  private const int TBM_GETCHANNELRECT = 0x400 + 26;
  private const int TBM_GETTHUMBRECT = 0x400 + 25;
  private struct RECT { public int left, top, right, bottom; }
  [DllImport("user32.dll", EntryPoint = "SendMessageW")]
  private static extern IntPtr SendMessageRect(IntPtr hWnd, int msg, IntPtr wp, ref RECT lp);
}

以下是表单中的示例用法,它从第一个刻度线到滑块指针绘制一条线:

private void myTrackBar1_ValueChanged(object sender, EventArgs e) {
  this.Invalidate();
}
protected override void  OnPaint(PaintEventArgs e) {
  var chan = this.RectangleToClient(myTrackBar1.RectangleToScreen(myTrackBar1.Channel));
  var slider = this.RectangleToClient(myTrackBar1.RectangleToScreen(myTrackBar1.Slider));
  e.Graphics.DrawLine(Pens.Black, chan.Left + slider.Width / 2, myTrackBar1.Bottom + 5,
    slider.Left + slider.Width / 2, myTrackBar1.Bottom + 5);
}