2016-05-06 19 views
0

簡単な質問ですが、どのように受け取った文字列をtextBoxに表示できますか?あなたの質問は、それらの詳細が含まれていないのでDataReceivedHandlerで受け取った表示データ

private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e) 
{ 
    SerialPort sp = (SerialPort)sender; 
    string indata = sp.ReadExisting();   
    //display here , textBox1.Text=indata (does not work)  
} 
+0

(http://stackoverflow.com/help)この[URL]を確認してください、あなたのコンテンツの品質を高めるために有用であろう –

答えて

0

、私は(does not work)部分についての仮定を行う必要があります。

そのような例外はありますか?

クロススレッド操作が有効でない:作成されたスレッド以外のスレッドからアクセスされるコントロール。

または

UiThreadsはあなたがいないことを意味しSTA(シングルスレッドアパートメント)として実行する必要がある静的な文脈で非静的フィールド 'textBox1テキストボックス' にアクセスできませんtextBox1DataReceivedHandlerとは異なるスレッドで '実行されているため'テキストボックスに直接アクセスします。

この問題を回避するには、textBox1を所有するスレッドのDispatcherをDispatcher、またはより正確に使用する必要があります。

はまた確認するそのDataReceivedHandlerはあなたがaccidentialy現在実行Dispatcherにディスパッチャの呼び出しを自分でデッドロックしていないことを、同じスレッドで実行することができます場合。

これを試してみてください:

//First, get rid if the 'static' you need the 
//instance of your window or whatever to access textBox1 
private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e) 
{ 
    SerialPort sp = (SerialPort)sender; 
    string indata = sp.ReadExisting();   

    SetOutput(indata); 
} 

private void SetOutput(string data) 
{ 
    //CheckAccess is a hidden Method, it might not me visible in Intellisense/AutoComplete 
    if(textBox1.CheckAccess()) 
    { 
     //textBox1 is directly accessible 
     textBox1.Text = data; 
    } 
    else 
    { 
     //Dispatcher call needed 
     textBox1.Dispatcher.BeginInvoke(
       new Action(() => 
       { 
        SetOut(data); 
       }) 
      ); 
    } 
} 
関連する問題