Home > Programmierung, Windows Mobile > Automatische Höhe für Labels im Compact Framework auf dem Pocket PC

Automatische Höhe für Labels im Compact Framework auf dem Pocket PC

Für ein kleines Projekt für Windows CE habe ich eine Methode gesucht um die Höhe eines Labels anhand des Inhalts automatisch zu setzen. Dabei habe ich hier eine Lösung in Visual Basic gefunden. Diese Lösung ist eigentlich recht elegant, da Sie API-Funktionen benutzt um das Rectangle zu zeichnen und die Höhe genau so zu bestimmen wie Sie auch später im Formular erscheinen würde wenn man z.B. den Text in ein Textfeld schreiben würde.

Hier eine Übersetzung in C#:

using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Drawing;
class Helper
{
    private struct RECT
    {
        public int Left;
        public int Top;
        public int Right;
        public int Bottom;
    }
    private const int DT_CALCRECT = 1024;
    private const int DT_CENTER = 1;
    private const int DT_LEFT = 0;
    private const int DT_RIGHT = 2;
    private const int DT_TOP = 0;
    private const int DT_WORDBREAK = 16;
    [DllImport("coredll.dll", CharSet = CharSet.Unicode,
        SetLastError = true)]
    private static extern int DeleteObject(IntPtr hObject);
    [DllImport("coredll.dll", CharSet = CharSet.Unicode,
        SetLastError = true)]
    private static extern int DrawText(IntPtr hdc, string lpStr,
        int nCount, ref RECT lpRect, int wFormat);
    [DllImport("coredll.dll", CharSet = CharSet.Unicode,
        SetLastError = true)]
    private static extern IntPtr SelectObject(IntPtr hdc,
        IntPtr hObject);
    /// <summary>
    /// Ändert die Höhe des Labels so, dass der Inhalt genau 
    /// reinpasst.
    /// </summary>
    /// <param name="label">Label dessen Höhe angepasst werden soll.
    /// </param>
    public static void AutoSizeLabelHeight(Label label)
    {
        RECT uRECT = new RECT();
        try
        {
            /*****************************************************
            * Create a Graphics object. We need a Graphics object 
            * so we can get a handle to a Device Context to be used
            * later in the DrawText API. However the Label control 
            * in CF2.0 does not support the CreateGraphics method,
            * so create the Graphics object from the form on which 
            * the Label is located.
            * Note: This can cause an exception when this routine 
            * is called from a Form's Resize event. Probably because
            * the form is not fully initialised and the Resize event
            * may be called one or more times during form
            * initialisation. Therefore, the entire routine is wrapped
            * in a Try/Catch block.
            *****************************************************/
            Graphics objGraphics = label.TopLevelControl.CreateGraphics();
            // Get the handle to the Device Context of the Graphics object
            IntPtr hDc = objGraphics.GetHdc();
            {
                // Get the handle to the Font of the Label
                IntPtr hFont = label.Font.ToHfont();
                // Apply the Font to the Graphics object
                IntPtr hFontOld = SelectObject(hDc, hFont);
                // Set the initial size of the Rect
                uRECT.Right = label.Width - 2;
                // Build the base format
                int lFormat = DT_CALCRECT | DT_WORDBREAK | DT_TOP;
                /*****************************************************
                 * Adjust the format to the Label's text alignment.
                 * Note: This probably isn't necessary as the horizontal 
                 * alignment of text shouldn't affect the text
                 * height calculation. But just in case...
                 *****************************************************/
                switch (label.TextAlign)
                {
                    case ContentAlignment.TopLeft:
                        lFormat = lFormat | DT_LEFT;
                        break;
                    case ContentAlignment.TopCenter:
                        lFormat = lFormat | DT_CENTER;
                        break;
                    case ContentAlignment.TopRight:
                        lFormat = lFormat | DT_RIGHT;
                        break;
                }
                // Calculate the Rect of the text
                if (DrawText(hDc, label.Text, -1, ref uRECT, lFormat)
                    != 0)
                {
                    // Success
                    // Apply the new height to the label
                    label.Height = uRECT.Bottom + 2;
                }
                // Cleanup
                // Set the Font of the Graphics object back to original
                SelectObject(hDc, hFontOld);
                // Delete the handle to the Font of the Label
                DeleteObject(hFont);
            }
            // Clean up the Graphics object
            objGraphics.Dispose();
        }
        catch
        {
            // Do nothing
            //Debug.WriteLine("AutoSizeLabelHeight failed.")
        }
    }
}
  1. Bisher keine Kommentare
  1. Bisher keine Trackbacks