NumericUpDown with Unit | Custom control | Field padding

前端 未结 1 511
深忆病人
深忆病人 2020-12-06 20:44

Im trying to create a custom control that inherits NumericUpDown to show a settable unit.

This is (visually) what I\'ve got so far:

相关标签:
1条回答
  • 2020-12-06 21:24

    NumericUpDown is a control which inherits from UpDownBase composite control. It contains an UpDownEdit and an UpDownButtons control. The UpDownEdit is a TextBox. You can change appearance of the control and its children. For example, you can add a Label to the textbox control and dock it to the right of TextBox, then set text margins of textbox by sending an EM_SETMARGINS message to get such result:

    Code

    using System;
    using System.ComponentModel;
    using System.Runtime.InteropServices;
    using System.Windows.Forms;
    public class ExNumericUpDown : NumericUpDown
    {
        [DllImport("user32.dll")]
        private static extern IntPtr SendMessage(IntPtr hwnd, int msg, int wParam, int lParam);
        private const int EM_SETMARGINS = 0xd3;
        private const int EC_RIGHTMARGIN = 2;
        private Label label;
        public ExNumericUpDown() : base()
        {
            var textBox = Controls[1];
            label = new Label() { Text = "MHz", Dock = DockStyle.Right, AutoSize = true };
            textBox.Controls.Add(label);
        }
        public string Label
        {
            get { return label.Text; }
            set { label.Text = value; if (IsHandleCreated) SetMargin(); }
        }
        protected override void OnHandleCreated(EventArgs e)
        {
            base.OnHandleCreated(e);
            SetMargin();
        }
        private void SetMargin()
        {
            SendMessage(Controls[1].Handle, EM_SETMARGINS, EC_RIGHTMARGIN, label.Width << 16);
        }
    }
    
    0 讨论(0)
提交回复
热议问题