2016-03-13 34 views
1

我想確定什麼最好的方法是確定在多行winforms TextBox控件上顯示的顯示(可見由於滾動)的行數。最準確的方法來計算winforms中顯示的行數TextBox控件

我使用目前的方法是非常不準確(因爲其他的方法我都試過):

var size = TextRenderer.MeasureText(
    textBox.Text, textBox.Font, textBox.ClientSize, TextFormatFlags.TextBoxControl); 
int lines = textBox.Lines.Length; 
int lineHeight = (size.Height/lines); 

// Value assigned to 'lines' does not reflect number of lines displayed: 
int lines = (textBox.Height/lineHeight); 

計算可見,必須考慮到的東西的行數的方法,如的滾動條文本框以及包括僅部分可見的行的文本框顯示的細微差別不顯示。

任何解決方案將不勝感激!

更新:

嘗試了以下計算的建議,但仍然有不準確的結果:

int lines = (textBox.Height/textBox.Font.Height); 

我做了一個簡單的測試程序,這裏是一個截圖,上面的兩個例子產生類似的結果:

screenshot of TextBox height calculation results

計算出的使用這兩種方法的行數通常不會反映隨着高度增加或減少而顯示的實際行數。

+0

而不是你的冗長計算,請嘗試'textBox.Font.Height'屬性作爲行高。 – nekavally

+0

謝謝你的建議;上述問題更新結果;仍然存在着不準確的線數計算。 – Lemonseed

+0

它不是直截了當的,TextBox使用未指定的邊距。你將不得不探測,使用TextBox.GetCharacterIndexFromPoint和GetLineIndexFromCharacterIndex ..嘿一個XY問題btw。 –

回答

1

您可以發送EM_GETRECT消息到文本框,然後將結果的高度RECT分爲文本框的Font.Height
結果會告訴您在可見區域TextBox中可以顯示多少行。

const int EM_GETRECT = 0xB2; 

[StructLayout(LayoutKind.Sequential)] 
struct RECT 
{ 
    public int Left, Top, Right, Bottom; 
} 

[DllImport("user32.dll", CharSet = CharSet.Auto)] 
static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, ref RECT lParam); 

和使用:

var rect = new RECT(); 
SendMessage(this.textBox1.Handle, EM_GETRECT, IntPtr.Zero, ref rect); 
var count = (rect.Bottom - rect.Top)/this.textBox1.Font.Height; 
0

代替測量,你可以做以下線的高度:

比方說^h是「看得見的」文本框的高度,^h是整個文本框的高度。讓我們打電話l可見線的數量,並且總數爲l

我們可以計算出比率h/H。我認爲同樣的比例也適用於行數。所以h/H應該等於l/L。您有h H L,您需要l

+0

謝謝你; yes this * should * work,but use'float H = TextRenderer.MeasureText(textBox.Text,textBox.Font,textBox.ClientSize,TextFormatFlags.TextBoxControl).Height; float h = textBox.Height; float L = textBox.Lines.Length; var l =(h * L/H);'仍然導致不準確的行數。 – Lemonseed

0

使用MeasureText確定線路和ClientSize的高度。文本框中高度的高度,可用於繪製文本:

 int lineHeight = TextRenderer.MeasureText("X", this.textbox1.Font).Height; 
     double linesPerPage = 1.0*this.textbox1.ClientSize.Height/lineHeight; 

這對於RichTextBox的工作方式相同。

相關問題