从静态类中的静态事件访问表单控件

时间:2014-12-07 19:08:22

标签: c# winforms

我在Form Proyect中使用语音识别,我有一个静态类,其函数初始化SR引擎。

在这个静态类中,我声明了public static form = new formX()

我的问题是,当我检测到语音识别事件时,我需要更新formX中的文本控件,但IDE说文本控件不存在于表单中,我认为是因为speechEngine使用单独的线程。

    static General()
    {

        General.ChatForm = new ChatForm();

    }


    public static void startSpeechRecognition()
    {

        // Setup grammar rules:
        GrammarBuilder builder = new GrammarBuilder();
        builder.AppendDictation();

        grammar = new Grammar(builder);

        // Initiate Recognizer and Setup Events:
        recognizer = new SpeechRecognitionEngine(/*new CultureInfo("es-ES")*/);
        recognizer.LoadGrammar(grammar); // Poner otro try aqui, si falla, es que no tiene configurado el sistema de voz
        recognizer.SetInputToDefaultAudioDevice(); // Poner un try aqui, si falla es que no tiene microfono configurado.

        recognizer.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(recognizer_SpeechRecognized);

        // Initialize Recognizer thread:
        RecognizerState = false;
        RecThread = new Thread(new ThreadStart(RecThreadFunction));
        RecThread.Start();

    }

    static void RecThreadFunction()
    {
        // this function is on separate thread (RecThread). This will loop the recognizer receive call.
        while (true)
        {
            try
            {
                recognizer.Recognize();
            }
            catch
            {
                // handle Errors. Most errors are caused from the recognizer not recognizing speech.
            }

        }
    }



    static void recognizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
    {
        // Event raised when the speech recognizer recognizes speech.
        /*
        if (!RecognizerState)
        {
            return;
        }
         * */


        General.ChatForm.richTextBox1.Text += (" " + e.Result.Text.ToLower());


    }

我的问题是General.ChatForm.richTextBox1.Text + =(&#34;&#34; + e.Result.Text.ToLower());,IDE显示&#34; System.windows。 Forms.Form不包含&#39; richtextBox1&#39;的定义。并且没有扩展方法&#39; richTextBox1&#39;接受System.Windows.Forms.Form类型的第一个参数可以找到&#34;

2 个答案:

答案 0 :(得分:1)

您需要设置ChatForm类型的静态字段或属性ChatForm,而不是Form

private ChatForm ChatForm;

答案 1 :(得分:0)

将表单中richtextBox1的修饰符更改为公开。

Changing modifier

如果General.ChatForm是Form的类型,请使用(General.ChatForm as ChatForm).richtextBox1或者Damir说将其类型更改为ChatForm