How to click OK button on a dialog

68 Views Asked by At

I need to programmatically click ok button on a dialog. I've already made a snippet with out clicking the dialog. I'm aware theoretically should not be needed but for some reason it only works if you click "OK" for certain features.

Snippet 1:

ConnPropsForm propsForm = new ConnPropsForm();

 editOutput.Text = "";

 propsForm.editUsername.Text = User;
 propsForm.editPassword.Text = Password;
 propsForm.editAddress.Text = _HOST;
 propsForm.editPort.Value = Convert.ToInt32(_PORT);
 propsForm.txtPrivateKey.Text = string.Empty;
 propsForm.txtPrivateKeyPassword.Text = string.Empty;
 propsForm.txtTrustedKeys.Text = string.Empty;

 client.Username = propsForm.editUsername.Text;
 client.Password = propsForm.editPassword.Text;
 client.TrustedKeysFile = propsForm.txtTrustedKeys.Text;

Snippet 1 is just setting up the Dialog Box. Nothing special here

Snippet 2:

if (propsForm.ShowDialog(this) == DialogResult.OK)
{
    editOutput.Text = "";

    client.Username = propsForm.editUsername.Text;
    client.Password = propsForm.editPassword.Text;

    if (propsForm.txtPrivateKey.Text != "")
    {
        try
        {
            Sshkeymanager keymanager = new Sshkeymanager();
            keymanager.ImportFromFile(propsForm.txtPrivateKey.Text, propsForm.txtPrivateKeyPassword.Text);

            client.Key = keymanager.Key;
        }
        catch (Exception E)
        {
            MessageBox.Show(E.Message);
        }
    }

    client.TrustedKeysFile = propsForm.txtTrustedKeys.Text;

    try
    {
        client.Connect(propsForm.editAddress.Text, (int)propsForm.editPort.Value);

        LoadRoot();
        UpdateControls();
    }
    catch (Exception E)
    {
        MessageBox.Show(E.Message);
    }
}

Snippet 2 is the magic. I want to test and see if "clicking OK makes a difference. Currently troubleshooting an issue with a bot i'm building. In case your wondering. The bots job is to literally just update a password every 30 days. In a perfect world I would not need a dialog and not need to click Ok button programmatically but the IT gods are mad at me currently. I thought about doing a loop to loop through each control until I found the "btnOk" button but I hope there is a better way.

2

There are 2 best solutions below

0
Michael Rourk On

In Winforms, if you have direct access to the button from where this is running you can just do this:

btnOk.PerformClick();
0
IV. On

As I understand it, you want the form to self-close with DialogResult.OK. If the form is being shown modally (because ShowDialog was invoked on it) then you can set the dialog result directly and the form will close as a result. For example, when this form is shown by ShowDialog it will self-close after a 10-second countdown.

closing in 10

Self-Close
public partial class ConnPropsForm : Form
{
    public ConnPropsForm() => InitializeComponent();
    protected override void OnVisibleChanged(EventArgs e)
    {
        base.OnVisibleChanged(e);
        if(Visible)
        {
            _ = ExecAutoClose();
        }
    }
    private async Task ExecAutoClose()
    {
        int remaining = 10;
        do
        {
            label1.Text = $"Closing in {remaining:d2}";
            await Task.Delay(TimeSpan.FromSeconds(1));
            remaining--;
        } while(Visible && remaining > 0);
        DialogResult = DialogResult.OK;
    }
}

The calling method can do the same thing. Here, the main form aborts the countdown after 5 seconds the first time (only) that ConnPropsForm is shown.

External-Close
public partial class MainForm : Form
{
    public MainForm()
    {
        InitializeComponent();
        Disposed += (sender, e) =>ConnPropsForm.Dispose();
        buttonShow.Click += (sender, e) =>
        {
            if (!ConnPropsForm.Visible)
            {
                Text = ConnPropsForm.ShowDialog(this).ToString();
            }
        };
    }
    protected override async void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
        BeginInvoke(() => Text = ConnPropsForm.ShowDialog(this).ToString());

        await Task.Delay(TimeSpan.FromSeconds(5));
        ConnPropsForm.DialogResult = DialogResult.Abort;
    }
    ConnPropsForm ConnPropsForm = new ConnPropsForm();
}