1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

form controll threading

Discussion in 'C++' started by Larsonator, Oct 5, 2010.

  1. Larsonator

    Larsonator New Member

    Joined:
    Oct 5, 2010
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    I realise this topic has been covered before,
    but i am struggling to grasp the concept of delegates and stuff.

    my program has a multi lines textbox, and a function (which runs on a different thread) that runs in a loop continuesly receiving data from a socket. this data comes in the form of a string, and it is made into a system.string, and is then appended to the textbox

    the problem i am having is that the textbox is created on thread1, where has the function is on thread2. trying to access the textbox from thread 2 makes baby jesus cry. I understand that this is where i need to use the invoke methods, and delegate functions, but as to implimenting these processing to solve my delema is still beyond my grasp.

    i can show you what i have so far in terms of relevant code

    Code:
    public ref class Form1 : public System::Windows::Forms::Form
    	{
    
    	public:
    		delegate void OutPutBoxAppend(System::String^ ms);
    		OutPutBoxAppend^ myDelegate;
    			
    		Form1(void)
    		{	
    			CONNECTED = false;
    			connectSockets();
    			myDelegate = gcnew OutPutBoxAppend(this, &Form1::OutPutBoxWork);
    			Application::Run(gcnew loginForm(commandSocket));
    			InitializeComponent();
    
    			Sleep(10);
    			Thread^ oThread = gcnew Thread(gcnew ParameterizedThreadStart(Form1::ThreadProc1));
    			oThread->Start(this);
    			//
    			//TODO: Add the constructor code here
    			//
    		}
    
    		void OutPutBoxWork(System::String^ ms)
    		{
    			this->ouputBox->AppendText(ms);	
    		}
    
    /////////////////////////////////////////////////////////////////////////////////////////////////////--code gap
    
    		static void ThreadProc1(System::Object ^obj)
    		{
    			Form1^ ob = (Form1^) obj;
    			
    			for(;; )
    			{
    				string recvStr;
    				if((recvStr = ob->recvData(ob->getMonSocket())) == "")
    				{
    					MessageBox::Show(L"could not receive stream");
    					break;
    				}else{
    					
    					using namespace System::Runtime::InteropServices;
    					recvStr.append("\r\n");
    					System::String^ ms;
    					ms = Marshal::PtrToStringAnsi(static_cast(const_cast(recvStr.c_str())));
    
    					if(ob->ouputBox->InvokeRequired)
    					{
    						OutPutBoxAppend ^d = gcnew OutPutBoxAppend(^ms);
    						ob->Invoke(ob->myDelegate);
    					}else{
    						ob->ouputBox->AppendText(ms);
    					}
    				}
    			}
    
    		}
    
    Edit: This obviously doesnt build, i was trying to addapt one of the examples givin on the msdn website.
     

Share This Page