2023/05/19(Fri) 23:37:30 編集(投稿者)
■No101958 (初心者 さん) に返信
> <やりたいこと>
> 個人001 : aaa abc 25
> 個人002 : bbb あああ 75
> 個人003 : ccc 哦哦哦 66
ゼロ幅スペースやサロゲートペアなどを考えると幅を求めるのは結構やっかいです。
面倒なことは知ってる人にやらせてみます。(つまり GDI に聞く。)
描画領域には余白があるので最初に半角2文字の幅から半角1文字の幅を引いて
1文字あたりの幅を求めます。残りが余白になるのでそれをもとに判定していきます、
Imports System.Globalization
Public Class Form1
Private _Graphics As Graphics = Graphics.FromHwnd(IntPtr.Zero)
Private _FixedFont As New Font("MS ゴシック", 9.75!, FontStyle.Regular)
Private _HalfCharWidth As Integer
Private _Padding As Integer
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim twoCharWidth As Integer = GetDrawWidth("AA")
Dim oneCharWidth As Integer = GetDrawWidth("A")
_HalfCharWidth = twoCharWidth - oneCharWidth
_Padding = twoCharWidth - _HalfCharWidth
ListBox1.Font = _FixedFont
ListBox1.Items.Clear()
ListBox1.Items.Add(EditItem("個人001", "aaa", "abc", "25"))
ListBox1.Items.Add(EditItem("個人002", "bbb", "あああ", "75"))
ListBox1.Items.Add(EditItem("個人003", "ccc", "哦哦哦", "66"))
End Sub
Private Sub Form1_FormClosed(sender As Object, e As FormClosedEventArgs) Handles Me.FormClosed
_Graphics.Dispose()
_Graphics = Nothing
_FixedFont.Dispose()
_FixedFont = Nothing
End Sub
Private Function EditItem(item1 As String, item2 As String, item3 As String, item4 As String) As String
Return RightPad(item1, 8) & ": " & RightPad(item2, 7) & RightPad(item3, 13) & item4
End Function
Private Function GetDrawWidth(text As String) As Integer
Return TextRenderer.MeasureText(_Graphics, text, _FixedFont).Width
End Function
Private Function RightPad(text As String, nLength As Integer) As String
Dim drawWidth As Integer = GetDrawWidth(text)
Dim needWidth As Integer = nLength * _HalfCharWidth + _Padding '必要な長さ
If drawWidth > needWidth Then
'必要な長さになるまで末尾を削る
Dim info As New StringInfo(text)
Dim length As Integer = info.LengthInTextElements - 1
While drawWidth > needWidth
text = info.SubstringByTextElements(0, length)
drawWidth = GetDrawWidth(text)
length -= 1
End While
End If
Return text & New String(" "c, (needWidth - drawWidth) \ _HalfCharWidth)
End Function
End Class