2008-09-18 7 views

Répondre

173

Ajouter une référence à Microsoft.VisualBasic, InputBox est dans l'espace de noms Microsoft.VisualBasic.Interaction:

string input = Microsoft.VisualBasic.Interaction.InputBox("Prompt", "Title", "Default", -1, -1); 
+7

Bah ... pistolet le plus rapide dans l'ouest haha ​​....de toute façon j'ai cherché la signature dans le navigateur d'objet et l'invite vient avant le titre, donc son "Prompt" d'abord, puis "Titre" .. le dernier numéro 2 est X/Y coordonnées pour afficher la boîte d'entrée – chakrit

+0

de l'utilisateur? – hims056

+3

@ hims056 'InputBox' ne supporte pas nativement les entrées masquées. Vous devrez lancer votre propre formulaire de saisie. –

0

Il n'y a rien de tel: je recommande de l'écrire pour vous-même et de l'utiliser quand vous en avez besoin.

3

Vous voulez dire InputBox? Regardez dans l'espace de noms Microsoft.VisualBasic.

C# et VB.Net partagent une bibliothèque commune. Si une langue peut l'utiliser, l'autre peut le faire.

7

Il n'y en a pas. Si vous voulez vraiment utiliser le VB InputBox en C#, vous pouvez. Ajoutez juste la référence à Microsoft.VisualBasic.dll et vous le trouverez là.

Mais je suggère à pas l'utiliser. C'est moche et obsolète IMO.

+15

Je pense que vous êtes trop gentil. C'est beaucoup plus moche et démodé que ça! – BlackWasp

+3

Impossible d'identifier le 'cancel' de' chaîne d'entrée vide' est en fait un bug IMO. –

4

Ajouter référence à Microsoft.VisualBasic et utiliser cette fonction:

string response = Microsoft.VisualBasic.Interaction.InputBox("What's 1+1?", "Title", "2", 0, 0); 

Le dernier numéro 2 est une position X/Y pour afficher la boîte de dialogue de saisie.

92

Pour résumer:

  • Il est none in C#.
  • Vous pouvez utiliser la boîte de dialogue à partir de Visual Basic en ajoutant une référence à Microsoft.VisualBasic:

    1. Dans l'Explorateur de solutions clic droit sur les Références dossier.
    2. Sélectionnez Ajouter Référence ...
    3. Dans l'onglet .NET (dans les nouveaux verions Visual Studio - onglet Assemblée) - sélectionnez Microsoft.VisualBasic
    4. Cliquez sur OK

Ensuite, vous pouvez utiliser le code mentionné précédemment:

string input = Microsoft.VisualBasic.Interaction.InputBox("Title", "Prompt", "Default", 0, 0); 

Cela dit, je suggère que vous considériez le besoin d'une boîte d'entrée en premier lieu. Les dialogues ne sont pas toujours la meilleure façon de faire les choses et parfois ils font plus de mal que de bien - mais cela dépend de la situation particulière.

+0

Vous pouvez utiliser la boîte de dialogue de C# en ajoutant cette référence. –

+0

Les boîtes d'entrée sont une aubaine pour tester ui ... –

+3

Oui, ils sont. Mais il me semble que dans la plupart des cas, ils sont mauvais dans le code d'expédition. –

2

Vous pouvez utiliser la boîte de dialogue Templet Exemple d'entrée suivante qui se trouve ici: link text

5

si vous ajoutez non seulement Microsoft.VisualBasic à votre liste de référence pour le projet, mais aussi vous devez déclarer « en utilisant Microsoft.VisualBasic; » il vous suffit donc d'utiliser 'Interaction.Inputbox ("...")' au lieu de Microsoft.VisualBasic.Interaction.Inputbox

+0

Si vous ne l'utilisez qu'une seule fois, cela ajoute de l'encombrement si l'OP décide qu'il ne veut plus l'InputBox. Aussi, cela devrait être un commentaire. – BalinKingOfMoria

3

Renvoie la chaîne entrée par l'utilisateur; chaîne vide s'ils ont frappé Annuler:

public static String InputBox(String caption, String prompt, String defaultText) 
    { 
     String localInputText = defaultText; 
     if (InputQuery(caption, prompt, ref localInputText)) 
     { 
      return localInputText; 
     } 
     else 
     { 
      return ""; 
     } 
    } 

Renvoie la String comme paramètre ref, retour true s'ils ont frappé OK ou false s'ils ont frappé Annuler:

public static Boolean InputQuery(String caption, String prompt, ref String value) 
    { 
     Form form; 
     form = new Form(); 
     form.AutoScaleMode = AutoScaleMode.Font; 
     form.Font = SystemFonts.IconTitleFont; 

     SizeF dialogUnits; 
     dialogUnits = form.AutoScaleDimensions; 

     form.FormBorderStyle = FormBorderStyle.FixedDialog; 
     form.MinimizeBox = false; 
     form.MaximizeBox = false; 
     form.Text = caption; 

     form.ClientSize = new Size(
        Toolkit.MulDiv(180, dialogUnits.Width, 4), 
        Toolkit.MulDiv(63, dialogUnits.Height, 8)); 

     form.StartPosition = FormStartPosition.CenterScreen; 

     System.Windows.Forms.Label lblPrompt; 
     lblPrompt = new System.Windows.Forms.Label(); 
     lblPrompt.Parent = form; 
     lblPrompt.AutoSize = true; 
     lblPrompt.Left = Toolkit.MulDiv(8, dialogUnits.Width, 4); 
     lblPrompt.Top = Toolkit.MulDiv(8, dialogUnits.Height, 8); 
     lblPrompt.Text = prompt; 

     System.Windows.Forms.TextBox edInput; 
     edInput = new System.Windows.Forms.TextBox(); 
     edInput.Parent = form; 
     edInput.Left = lblPrompt.Left; 
     edInput.Top = Toolkit.MulDiv(19, dialogUnits.Height, 8); 
     edInput.Width = Toolkit.MulDiv(164, dialogUnits.Width, 4); 
     edInput.Text = value; 
     edInput.SelectAll(); 


     int buttonTop = Toolkit.MulDiv(41, dialogUnits.Height, 8); 
     //Command buttons should be 50x14 dlus 
     Size buttonSize = Toolkit.ScaleSize(new Size(50, 14), dialogUnits.Width/4, dialogUnits.Height/8); 

     System.Windows.Forms.Button bbOk = new System.Windows.Forms.Button(); 
     bbOk.Parent = form; 
     bbOk.Text = "OK"; 
     bbOk.DialogResult = DialogResult.OK; 
     form.AcceptButton = bbOk; 
     bbOk.Location = new Point(Toolkit.MulDiv(38, dialogUnits.Width, 4), buttonTop); 
     bbOk.Size = buttonSize; 

     System.Windows.Forms.Button bbCancel = new System.Windows.Forms.Button(); 
     bbCancel.Parent = form; 
     bbCancel.Text = "Cancel"; 
     bbCancel.DialogResult = DialogResult.Cancel; 
     form.CancelButton = bbCancel; 
     bbCancel.Location = new Point(Toolkit.MulDiv(92, dialogUnits.Width, 4), buttonTop); 
     bbCancel.Size = buttonSize; 

     if (form.ShowDialog() == DialogResult.OK) 
     { 
      value = edInput.Text; 
      return true; 
     } 
     else 
     { 
      return false; 
     } 
    } 

    /// <summary> 
    /// Multiplies two 32-bit values and then divides the 64-bit result by a 
    /// third 32-bit value. The final result is rounded to the nearest integer. 
    /// </summary> 
    public static int MulDiv(int nNumber, int nNumerator, int nDenominator) 
    { 
     return (int)Math.Round((float)nNumber * nNumerator/nDenominator); 
    } 

Remarque: Tout code est publié dans le domaine public. Aucune attribution requise.

+0

public static int MulDiv (nombre entier, numérateur int, dénominateur int) { return (int) (((long) nombre * numérateur + (dénominateur >> 1))/dénominateur); } –

+0

Qu'est-ce que '' Toolkit''? –

+1

@markusL Toolkit était ma classe qui détient une implémentation de 'MulDiv'. Vous pouvez voir le commentaire de Peter pour un exemple d'implémentation de 'MulDiv'. –

78

Création dynamique d'une boîte de dialogue. Vous pouvez personnaliser à votre goût.

Remarque il n'y a pas de dépendance externe ici que WinForm

private static DialogResult ShowInputDialog(ref string input) 
    { 
     System.Drawing.Size size = new System.Drawing.Size(200, 70); 
     Form inputBox = new Form(); 

     inputBox.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; 
     inputBox.ClientSize = size; 
     inputBox.Text = "Name"; 

     System.Windows.Forms.TextBox textBox = new TextBox(); 
     textBox.Size = new System.Drawing.Size(size.Width - 10, 23); 
     textBox.Location = new System.Drawing.Point(5, 5); 
     textBox.Text = input; 
     inputBox.Controls.Add(textBox); 

     Button okButton = new Button(); 
     okButton.DialogResult = System.Windows.Forms.DialogResult.OK; 
     okButton.Name = "okButton"; 
     okButton.Size = new System.Drawing.Size(75, 23); 
     okButton.Text = "&OK"; 
     okButton.Location = new System.Drawing.Point(size.Width - 80 - 80, 39); 
     inputBox.Controls.Add(okButton); 

     Button cancelButton = new Button(); 
     cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; 
     cancelButton.Name = "cancelButton"; 
     cancelButton.Size = new System.Drawing.Size(75, 23); 
     cancelButton.Text = "&Cancel"; 
     cancelButton.Location = new System.Drawing.Point(size.Width - 80, 39); 
     inputBox.Controls.Add(cancelButton); 

     inputBox.AcceptButton = okButton; 
     inputBox.CancelButton = cancelButton; 

     DialogResult result = inputBox.ShowDialog(); 
     input = textBox.Text; 
     return result; 
    } 

utilisation

string input="hede"; 
ShowInputDialog(ref input); 
+1

+1, serait également bien si elle a accepté les touches ESC et ENTER –

+2

OK, très facile, je l'ai trouvé: inputBox.AcceptButton = okButton; inputBox.CancelButton = cancelButton; –

+1

Travailler! Mieux que la solution VB. Merci beehorf! –

1

Sans ajouter une référence à Microsoft.VisualBasic:

// "dynamic" requires reference to Microsoft.CSharp 
Type tScriptControl = Type.GetTypeFromProgID("ScriptControl"); 
dynamic oSC = Activator.CreateInstance(tScriptControl); 

oSC.Language = "VBScript"; 
string sFunc = @"Function InBox(prompt, title, default) 
InBox = InputBox(prompt, title, default)  
End Function 
"; 
oSC.AddCode(sFunc); 
dynamic Ret = oSC.Run("InBox", "メッセージ", "タイトル", "初期値"); 

Voir ces pour plus informations:
ScriptControl
MsgBox in JScript
Input and MsgBox in JScript

2,0 .NET:

string sFunc = @"Function InBox(prompt, title, default) 
InBox = InputBox(prompt, title, default)  
End Function 
"; 

Type tScriptControl = Type.GetTypeFromProgID("ScriptControl"); 
object oSC = Activator.CreateInstance(tScriptControl); 

// https://github.com/mono/mono/blob/master/mcs/class/corlib/System/MonoType.cs 
// System.Reflection.PropertyInfo pi = tScriptControl.GetProperty("Language", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.CreateInstance| System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.SetProperty | System.Reflection.BindingFlags.IgnoreCase); 
// pi.SetValue(oSC, "VBScript", null); 

tScriptControl.InvokeMember("Language", System.Reflection.BindingFlags.SetProperty, null, oSC, new object[] { "VBScript" }); 
tScriptControl.InvokeMember("AddCode", System.Reflection.BindingFlags.InvokeMethod, null, oSC, new object[] { sFunc }); 
object ret = tScriptControl.InvokeMember("Run", System.Reflection.BindingFlags.InvokeMethod, null, oSC, new object[] { "InBox", "メッセージ", "タイトル", "初期値" }); 
Console.WriteLine(ret); 
1

j'ai pu y parvenir en codant mon propre. Je n'aime pas m'étendre dans de grandes bibliothèques et m'en servir pour quelque chose de rudimentaire.

Forme et Designer:

public partial class InputBox 
    : Form 
{ 

    public String Input 
    { 
     get { return textInput.Text; } 
    } 

    public InputBox() 
    { 
     InitializeComponent(); 
    } 

    private void button2_Click(object sender, EventArgs e) 
    { 
     DialogResult = System.Windows.Forms.DialogResult.OK; 
    } 

    private void button1_Click(object sender, EventArgs e) 
    { 
     DialogResult = System.Windows.Forms.DialogResult.Cancel; 
    } 

    private void InputBox_Load(object sender, EventArgs e) 
    { 
     this.ActiveControl = textInput; 
    } 

    public static DialogResult Show(String title, String message, String inputTitle, out String inputValue) 
    { 
     InputBox inputBox = null; 
     DialogResult results = DialogResult.None; 

     using (inputBox = new InputBox() { Text = title }) 
     { 
      inputBox.labelMessage.Text = message; 
      inputBox.splitContainer2.SplitterDistance = inputBox.labelMessage.Width; 
      inputBox.labelInput.Text = inputTitle; 
      inputBox.splitContainer1.SplitterDistance = inputBox.labelInput.Width; 
      inputBox.Size = new Size(
       inputBox.Width, 
       8 + inputBox.labelMessage.Height + inputBox.splitContainer2.SplitterWidth + inputBox.splitContainer1.Height + 8 + inputBox.button2.Height + 12 + (50)); 
      results = inputBox.ShowDialog(); 
      inputValue = inputBox.Input; 
     } 

     return results; 
    } 

    void labelInput_TextChanged(object sender, System.EventArgs e) 
    { 
    } 

} 

partial class InputBox 
{ 
    /// <summary> 
    /// Required designer variable. 
    /// </summary> 
    private System.ComponentModel.IContainer components = null; 

    /// <summary> 
    /// Clean up any resources being used. 
    /// </summary> 
    /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> 
    protected override void Dispose(bool disposing) 
    { 
     if (disposing && (components != null)) 
     { 
      components.Dispose(); 
     } 
     base.Dispose(disposing); 
    } 

    #region Windows Form Designer generated code 

    /// <summary> 
    /// Required method for Designer support - do not modify 
    /// the contents of this method with the code editor. 
    /// </summary> 
    private void InitializeComponent() 
    { 
     this.labelMessage = new System.Windows.Forms.Label(); 
     this.button1 = new System.Windows.Forms.Button(); 
     this.button2 = new System.Windows.Forms.Button(); 
     this.labelInput = new System.Windows.Forms.Label(); 
     this.textInput = new System.Windows.Forms.TextBox(); 
     this.splitContainer1 = new System.Windows.Forms.SplitContainer(); 
     this.splitContainer2 = new System.Windows.Forms.SplitContainer(); 
     ((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).BeginInit(); 
     this.splitContainer1.Panel1.SuspendLayout(); 
     this.splitContainer1.Panel2.SuspendLayout(); 
     this.splitContainer1.SuspendLayout(); 
     ((System.ComponentModel.ISupportInitialize)(this.splitContainer2)).BeginInit(); 
     this.splitContainer2.Panel1.SuspendLayout(); 
     this.splitContainer2.Panel2.SuspendLayout(); 
     this.splitContainer2.SuspendLayout(); 
     this.SuspendLayout(); 
     // 
     // labelMessage 
     // 
     this.labelMessage.AutoSize = true; 
     this.labelMessage.Location = new System.Drawing.Point(3, 0); 
     this.labelMessage.MaximumSize = new System.Drawing.Size(379, 0); 
     this.labelMessage.Name = "labelMessage"; 
     this.labelMessage.Size = new System.Drawing.Size(50, 13); 
     this.labelMessage.TabIndex = 99; 
     this.labelMessage.Text = "Message"; 
     // 
     // button1 
     // 
     this.button1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); 
     this.button1.Location = new System.Drawing.Point(316, 126); 
     this.button1.Name = "button1"; 
     this.button1.Size = new System.Drawing.Size(75, 23); 
     this.button1.TabIndex = 3; 
     this.button1.Text = "Cancel"; 
     this.button1.UseVisualStyleBackColor = true; 
     this.button1.Click += new System.EventHandler(this.button1_Click); 
     // 
     // button2 
     // 
     this.button2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); 
     this.button2.Location = new System.Drawing.Point(235, 126); 
     this.button2.Name = "button2"; 
     this.button2.Size = new System.Drawing.Size(75, 23); 
     this.button2.TabIndex = 2; 
     this.button2.Text = "OK"; 
     this.button2.UseVisualStyleBackColor = true; 
     this.button2.Click += new System.EventHandler(this.button2_Click); 
     // 
     // labelInput 
     // 
     this.labelInput.AutoSize = true; 
     this.labelInput.Location = new System.Drawing.Point(3, 6); 
     this.labelInput.Name = "labelInput"; 
     this.labelInput.Size = new System.Drawing.Size(31, 13); 
     this.labelInput.TabIndex = 99; 
     this.labelInput.Text = "Input"; 
     this.labelInput.TextChanged += new System.EventHandler(this.labelInput_TextChanged); 
     // 
     // textInput 
     // 
     this.textInput.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) 
     | System.Windows.Forms.AnchorStyles.Right))); 
     this.textInput.Location = new System.Drawing.Point(3, 3); 
     this.textInput.Name = "textInput"; 
     this.textInput.Size = new System.Drawing.Size(243, 20); 
     this.textInput.TabIndex = 1; 
     // 
     // splitContainer1 
     // 
     this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill; 
     this.splitContainer1.FixedPanel = System.Windows.Forms.FixedPanel.Panel2; 
     this.splitContainer1.IsSplitterFixed = true; 
     this.splitContainer1.Location = new System.Drawing.Point(0, 0); 
     this.splitContainer1.Name = "splitContainer1"; 
     // 
     // splitContainer1.Panel1 
     // 
     this.splitContainer1.Panel1.Controls.Add(this.labelInput); 
     // 
     // splitContainer1.Panel2 
     // 
     this.splitContainer1.Panel2.Controls.Add(this.textInput); 
     this.splitContainer1.Size = new System.Drawing.Size(379, 50); 
     this.splitContainer1.SplitterDistance = 126; 
     this.splitContainer1.TabIndex = 99; 
     // 
     // splitContainer2 
     // 
     this.splitContainer2.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) 
     | System.Windows.Forms.AnchorStyles.Left) 
     | System.Windows.Forms.AnchorStyles.Right))); 
     this.splitContainer2.IsSplitterFixed = true; 
     this.splitContainer2.Location = new System.Drawing.Point(12, 12); 
     this.splitContainer2.Name = "splitContainer2"; 
     this.splitContainer2.Orientation = System.Windows.Forms.Orientation.Horizontal; 
     // 
     // splitContainer2.Panel1 
     // 
     this.splitContainer2.Panel1.Controls.Add(this.labelMessage); 
     // 
     // splitContainer2.Panel2 
     // 
     this.splitContainer2.Panel2.Controls.Add(this.splitContainer1); 
     this.splitContainer2.Size = new System.Drawing.Size(379, 108); 
     this.splitContainer2.SplitterDistance = 54; 
     this.splitContainer2.TabIndex = 99; 
     // 
     // InputBox 
     // 
     this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); 
     this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; 
     this.ClientSize = new System.Drawing.Size(403, 161); 
     this.Controls.Add(this.splitContainer2); 
     this.Controls.Add(this.button2); 
     this.Controls.Add(this.button1); 
     this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; 
     this.MaximizeBox = false; 
     this.MinimizeBox = false; 
     this.Name = "InputBox"; 
     this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; 
     this.Text = "Title"; 
     this.TopMost = true; 
     this.Load += new System.EventHandler(this.InputBox_Load); 
     this.splitContainer1.Panel1.ResumeLayout(false); 
     this.splitContainer1.Panel1.PerformLayout(); 
     this.splitContainer1.Panel2.ResumeLayout(false); 
     this.splitContainer1.Panel2.PerformLayout(); 
     ((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).EndInit(); 
     this.splitContainer1.ResumeLayout(false); 
     this.splitContainer2.Panel1.ResumeLayout(false); 
     this.splitContainer2.Panel1.PerformLayout(); 
     this.splitContainer2.Panel2.ResumeLayout(false); 
     ((System.ComponentModel.ISupportInitialize)(this.splitContainer2)).EndInit(); 
     this.splitContainer2.ResumeLayout(false); 
     this.ResumeLayout(false); 

    } 

    #endregion 

    private System.Windows.Forms.Label labelMessage; 
    private System.Windows.Forms.Button button1; 
    private System.Windows.Forms.Button button2; 
    private System.Windows.Forms.Label labelInput; 
    private System.Windows.Forms.TextBox textInput; 
    private System.Windows.Forms.SplitContainer splitContainer1; 
    private System.Windows.Forms.SplitContainer splitContainer2; 
} 

Utilisation:

String output = ""; 

result = System.Windows.Forms.DialogResult.None; 

result = InputBox.Show(
    "Input Required", 
    "Please enter the value (if available) below.", 
    "Value", 
    out output); 

if (result != System.Windows.Forms.DialogResult.OK) 
{ 
    return; 
} 

RemarqueCet présente un peu de dimensionnement automatique pour le garder assez basé sur la quantité de texte que vous demandez afficher. Je sais aussi qu'il manque des cloches et des sifflets, mais c'est un grand pas en avant pour ceux qui font face au même dilemme.

Questions connexes