How to remove the focus from a Windows Forms control

0

I'm working on a Windows Forms app in which I have a form with a button and a TextBox what I want is that when I press the button to do a process when I finish giving the focus to a TextBox.

The code I use is the following:

private void OnAplicarDescuento(SelectedAplicarDescuento obj)
    {
        if (obj.Descuento >= 0 && obj.PrecioVenta != 0)
        {
            txtDescuento.Text = $"{obj.Descuento:N2}";
            txtPrecioVenta.Text = $"{obj.PrecioVenta:N2}";

            // Trato de darle el foco al control Textbox.
            Utilidades.ChangeControlStyles(btnAplicarDescuento, ControlStyles.StandardClick, false);
            ActiveControl = txtPrecioVenta;
            txtPrecioVenta.Select();
        }
    }

Method

// Para perder el foco de un control
    public static void ChangeControlStyles(Control ctrl, ControlStyles flag, bool value)
    {
        MethodInfo method = ctrl.GetType().GetMethod("SetStyle", BindingFlags.Instance | BindingFlags.NonPublic);
        if (method != null)
            method.Invoke(ctrl, new object[] { flag, value });
    }

The image where I want to remove the focus from the button is only the focus when I click on another control.

    
asked by Pedro Ávila 29.09.2018 в 16:29
source

3 answers

0

I managed to solve it in the following way: Changing focus when returning from the event.

var argPrecioBase = new ConstructorArgument("precioBase", Convert.ToDecimal(txtPrecioBase.Text));
            var frm = CompositionRoot.Resolve<FrmAplicarDescuento>(argPrecioBase);
            _hub.Subscribe<SelectedAplicarDescuento>(OnAplicarDescuento);
            frm.ShowDialog();
            ActiveControl = txtPrecioVenta;
            txtPrecioVenta.Select();

Greetings!

    
answered by 29.09.2018 в 18:13
0

Use the focus() method. One would think that select() does, but it's not like that.

Also, look at the answer to this question: Differences between Select, Focus and BringToFront methods

private void OnAplicarDescuento(SelectedAplicarDescuento obj)
{
    if (obj.Descuento >= 0 && obj.PrecioVenta != 0)
    {
        txtDescuento.Text = $"{obj.Descuento:N2}";
        txtPrecioVenta.Text = $"{obj.PrecioVenta:N2}";

        // Trato de darle el foco al control Textbox.
        txtPrecioVenta.focus();
    }
}
    
answered by 29.09.2018 в 18:20
-1
private bool aplicardescuento(object SelectedAplicarDescuento )
    {
        //Agregar codigo
        return true;
    }
 private void ayudaToolStripButton_Click(object sender, EventArgs e)
    {
        object obj= new object();
            if (aplicardescuento(obj))
            {
                textBox1.Select();
            }
            else
        {
            //otra tarea
        }
    }
    
answered by 29.09.2018 в 16:45