简体   繁体   中英

Can I add controls to the C# MessageBox?

Could I add some custom control to the standard Message Box for read input value, for example text fields for user name and password, or I should create custom winform with "Ok,Cancel" buttons and text fields?

Related: Which control to use for quick text input (inputbox)?

you can use the Interaction.InputBox method wich is located in the Microsoft.VisualBasic namespace

try this

 Microsoft.VisualBasic.Interaction.InputBox("Enter a Value Here", "Title", "Your Default Text",200,100);

You will need to create a custom WinForm to do this. You can make it work the same way as a MessageBox by returning a DialogResult on the Show method.

Create your own.

Creating a custom modal (or otherwise) input dialog isn't all that difficult and you can built the extensibility you need for reuse.

public class ValueHolder {
    public string SomeInput { get; set; }
    public DialogResult Result { get; set; }
}

public class GimmeValues : Form {
    //... HAS A TEXTBOX and Okay Buttons...

    private GimmeValues() {        
        okButton.DialogResult = DialogResult.OK;
        cancelButton.DialogResult = DialogResult.Cancel;
        // ... other stuff
    }

    public static ValueHolder GetInput(IWin32Window owner) {
        using (GimmeValues values = new GimmeValues()) {
            DialogResult result = values.ShowDialog(owner);
            return new ValueHolder { 
                SomeInput = values.Textbox1.Text,
                Result = result
            };
        }
    }
}

Okay I just wrote that all in this editor so forgive any syntax mistakes.
You could do something like the above but clean it up a little, add the extensibility you need (in terms of buttons and inputs showing that you need etc)... then just call it like ValueHolder value = GimmeValues.GetInput(this); where this would represent an IWin32Window ...

The resulting value of value would be the selected nonsense and you could perform your logic..

if(value.Result == DialogResult.OK && !string.IsNullOrEmpty(value.SomeInput)){
    //TODO: Place logic....
}

You'll have to create a custom form to handle that.

If you want the Form to behave like MessageBox, just create a static Show() method on your Form that creates an instance and shows the box to the user. That static method can also handle returning the values you are interested in from your custom form (much like DialogResult).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM