我需要計算顯示文本的Windows窗體寬度。 形式寬度顯然是在像素所以你只是想獲得文本的寬度,以像素爲單位,但是,這並不工作:計算顯示文本的Windows窗體寬度
animationForm.Width = TextRenderer.MeasureText(_caption, animationForm.Font).Width;
計算的表格寬度來說太小了(切斷文本) - 這裏發生了什麼? MeasureText使用像素,表單寬度以像素爲單位。
這工作好,但我不認爲這是正確的:
animationForm.Width = (int)(_caption.Length * animationForm.Font.Size);
幫助,將不勝感激。
AnimationPic - 圖片框, 標題上一個標籤組
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace PrlSystems.MaimInvoicing.Forms
{
public partial class ProgressIndicatorForm : Form
{
private volatile bool _animating = false;
private Form _parent;
private string _caption = "";
private object _mutex = new object();
public ProgressIndicatorForm(Form parent)
{
InitializeComponent();
_parent = parent;
}
public string Caption
{
set { _caption = value; }
get { return _caption; }
}
public void StartAnimation()
{
lock (_mutex)
{
if (!_animating)
{
if (_parent != null)
{
_parent.Cursor = Cursors.WaitCursor;
_parent.Enabled = false;
}
_animating = true;
_SpawnAnimationThread();
}
}
}
public void StopAnimation()
{
lock (_mutex)
{
if (_animating)
{
_animating = false; // stop animation thread
if (_parent != null)
{
// restore parent form UI
_parent.Cursor = Cursors.Default;
_parent.Enabled = true;
_parent.Activate();
}
}
}
}
private void _SpawnAnimationThread()
{
Thread animationThread = new Thread(new ThreadStart(_Animate));
animationThread.Priority = ThreadPriority.Normal;
animationThread.IsBackground = true; // should terminate when application ends
animationThread.Start();
}
private void _Animate()
{
ProgressIndicatorForm animationForm = new ProgressIndicatorForm(_parent);
animationForm.CaptionLabel.Text = _caption;
animationForm.StartPosition = FormStartPosition.CenterScreen;
animationForm.TopMost = true;
animationForm.Width = _CalculateFormWidth(animationForm);
animationForm.Show();
while (_animating)
{
animationForm.CaptionLabel.Text = _caption;
animationForm.Width = _CalculateFormWidth(animationForm);
animationForm.BringToFront();
animationForm.Refresh();
}
animationForm.Close();
animationForm.Dispose();
}
private int _CalculateFormWidth(ProgressIndicatorForm animationForm)
{
int width = AnimationPic.Location.X + AnimationPic.Width +
TextRenderer.MeasureText(_caption, animationForm.Font).Width;
return width;
}
}
}
形象設計師:
我要澄清一些我遺漏的東西,但這很重要。我也有動畫片。以下是整個公式:int width = AnimationPic.Location.X + AnimationPic.Width + TextRenderer.MeasureText(_caption,animationForm.Font).Width; – ActiveX 2011-05-18 14:08:35