簡體   English   中英

我如何等到字符串返回值?

[英]How do i wait until a String returns a value?

我有一個使用KeyPress事件向新Label添加新字符的程序,類似於控制台應用程序。 我需要在程序中添加一個Input方法,因此當我按Enter而不是執行函數時,它將返回一個字符串。 我試圖使KeyPress事件返回一個字符串,但是由於明顯的原因它不起作用,如何使它起作用?

注意:“返回字符串”是指;

如果我在哪里要求Console等待輸入,我仍將使用KeyPress事件,但它將返回用戶的字符串/輸入。

希望您能理解我已經編寫的代碼,請注意它會擴展到其他代碼中

我的KeyPress事件處理程序:

private void Form1_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (e.KeyChar == '\b') // Backspace
        {
            if (ll.Text != "_" && ActualText != "") // Are there any characters to remove?
            {
                ActualText = ll.Text.Substring(0, ActualText.Length - 1);
                ll.Text = ActualText + "_";
            }

        }
        else
            if (e.KeyChar == (char)13)
            {
                if (!inputmode)
                {
                    foreach (KeyValuePair<string, Action> cm in Base.Command())
                    {

                        if (ActualText == cm.Key)
                        {
                            print(ActualText);
                            cm.Value();

                        }
                    }
                }
                else
                {
                    inputmode = false;
                    lastInput = ActualText;
                    print("Input >> "+lastInput); 
                }
                ActualText = "";
                ll.Text = ActualText + "_";
            }
            else
            if (!Char.IsControl(e.KeyChar)) // Ignore control chars such as Enter.
            {
                ActualText = ActualText + e.KeyChar.ToString();
                ll.Text = ActualText + "_";
            }
    }

您的問題尚不清楚,但是如果我做對了,那么解決方案是代替返回字符串,而您顯然不能在KeyPress事件中返回字符串,而是引發自己的事件,如下所示

public delegate void EnterPressedHndlr(string myString);

public partial class Form1 : Form
{
  public event EnterPressedHndlr EnterPressed;

  void Form1_KeyPress(object sender, KeyPressEventArgs e)
  {
     //your calculation
     if (EnterPressed != null)
     {
        EnterPressed("your data");
     }
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM