dimanche 31 mai 2015

Place (locate) a CheckBox on the Form programmatically

I'm trying to create a MessageBox with an input field and a checkbox. Could you please help me to locate the CheckBox correctly? Here's my code:

public static DialogResult InputBox(string title, string promptText, ref string value, out bool isChecked)
{
    var form = new Form();
    var label = new Label();
    var textBox = new TextBox();
    var btnOk = new Button();
    var btnCancel = new Button();
    var checkBox = new CheckBox();

    form.Text = title;
    label.Text = promptText;
    textBox.Text = value;
    checkBox.Checked = false;

    checkBox.Text = @"Tick this:";
    btnOk.Text = @"Save";
    btnCancel.Text = @"Cancel";
    btnOk.DialogResult = System.Windows.Forms.DialogResult.OK;
    btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;

    label.SetBounds(9, 20, 372, 13);
    textBox.SetBounds(12, 36, 372, 20);
    checkBox.SetBounds(12, 42, 372, 13);
    btnOk.SetBounds(228,72,75,23);
    btnCancel.SetBounds(309, 72, 75, 23);

    label.AutoSize = true;
    checkBox.Anchor = checkBox.Anchor | AnchorStyles.Right;
    textBox.Anchor = textBox.Anchor | AnchorStyles.Right;
    btnOk.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
    btnCancel.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;

    //form.ClientSize = new Size(396, 107);
    form.ClientSize = new Size(396, 127);
    form.Controls.AddRange(new Control[] {label, textBox, checkBox, btnOk, btnCancel});
    form.ClientSize = new Size(Math.Max(300, label.Right + 10), form.ClientSize.Height);
    form.FormBorderStyle = FormBorderStyle.FixedDialog;
    form.StartPosition = FormStartPosition.CenterScreen;
    form.MinimizeBox = false;
    form.MaximizeBox = false;
    form.AcceptButton = btnOk;
    form.CancelButton = btnCancel;

    var dialogResult = form.ShowDialog();
    value = textBox.Text;
    isChecked = checkBox.Checked;
    return dialogResult;
}

And here's how I call the method:

        if (InputBox("Save", "Name: ", ref value, out isChecked) != DialogResult.OK)
            return;

The thing is that without the CheckBox everything works fine, but when I try to add the CheckBox, I can't locate it normally (I need it just below the input field). So could you help me with placing this checkbox correctly?




Aucun commentaire:

Enregistrer un commentaire