Reputation: 67223
I'm writing a WinForms user control. My plan is to allow the caller to modify the control's font but enforce that the font is always a fixed-width font.
I then need to position a caret horizontally within the control. When I did this in C++, I used GetTextMetrics()
and TEXTMETRIC.tmAveCharWidth
. But after spending a bunch of time this weekend, I've been unable to duplicate this in C#/WinForms.
I know there is a way to declare it so I can call GetTextMetrics()
directly. But I was hoping for a .NET way to do this. (And, if not, does someone have the correct syntax to declare this API function in .NET)
Upvotes: 1
Views: 463
Reputation: 73253
This works from a Windows Form:
TextMetrics metrics;
var renderer = new VisualStyleRenderer(VisualStyleElement.Window.Dialog.Normal);
using (var context = this.CreateGraphics() as IDeviceContext)
{
var metrics = renderer.GetTextMetrics(context);
}
var averageWidth = metrics.AverageCharWidth;
Upvotes: 2