[問題] 有關於Picturebox以及執行緒問題

看板C_and_CPP (C/C++)作者 (阿維)時間12年前 (2013/09/10 16:51), 編輯推噓0(004)
留言4則, 2人參與, 最新討論串1/2 (看更多)
我有一個程式 他是要將影片讀進來 然後我要使用Picturebox畫出來 有點長 我盡量寫詳細一點 所以我寫的簡單的class 大概是這樣 ref class StreamReadShow { public: System::Drawing::Bitmap^ _bmpImg ; System::Windows::Forms::PictureBox^ pictureBox; StreamReadShow( System::Windows::Forms::PictureBox^ pB ) { pictureBox = pB ;//指定哪一個picturebox } void StreamReadShowProcess() { while(true) { if(cvGrabFrame(capture )) { //讀影片 將影片資料取出儲存到_bmpImg //讀影片那段就略過.....反正最後可以得到_bmpImg //BMP放到指定的picturebox pictureBox->Image = _bmpImg ; pictureBox->Refresh(); } } } 我省略一些東西 這個class我說明一下 大概就是我會從外面傳進指定的PictureBox物件 然後把影片結取出來的bmp畫上指定的PictureBox 所以程式大概就會出現播放影片的效果 而呼叫這個class方法我是寫在Form介面的按鍵事件 所以理所當然按下按鍵事件 影片會播放 但是程式也會因為讀影片的迴圈給鎖住 我這邊使用執行緒 解決這問題 //起始物件 並指定要畫在哪一個picturebox StreamReadShow^ SRS = gcnew StreamReadShow( pictureBox1) ; //執行緒 ThreadStart^ threadDelegate = gcnew ThreadStart( SRS, &StreamReadShow::StreamReadShowProcess ); Thread^ newThread = gcnew Thread( threadDelegate ); newThread->Start(); 使用執行緒去執行StreamReadShowProcess這個影片迴圈 問題來了 我發現執行到 pictureBox->Image = _bmpImg ; pictureBox->Refresh(); 就會錯誤 Additional information: Object is currently in use elsewhere. Additional information: Cross-thread operation not valid: Control 'pictureBox1' accessed from a thread other than the thread it was created on 頭很大 我研究一下午 好像事執行緒問題 拿掉事沒問題 請問各位先進 有沒有辦法去解決這樣的問題 真的搞好久 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 1.34.221.115

09/10 17:14, , 1F
抱歉我沒看完. 但錯誤訊息是你應該使用委派 (delegate)
09/10 17:14, 1F

09/10 17:17, , 2F
通過 invoke 之類的讓 new 這個控制項的 thread 負責去改他.
09/10 17:17, 2F

09/10 17:21, , 3F
09/10 17:21, 3F

09/10 23:11, , 4F
(Begin)Invoke、AsyncOperation、SynchronizationContext
09/10 23:11, 4F
文章代碼(AID): #1IBjsDxF (C_and_CPP)
文章代碼(AID): #1IBjsDxF (C_and_CPP)