So i'm a bit new to C++(4-6 months so far + learning from books(not teachers)) and I understand this problem is most likely a result of my misunderstandings but I still can't figure it out after googling a lot of search terms... I also tried stackoverflow and read: Cross-thread operation not valid: Control 'Form1' accessed from a thread other than the thread it was created on Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on Best Way to Invoke Any Cross-Threaded Code? and I attempted to create a solution for this(which you can see below), but I failed to convert the code from c# to c++(I am not a C# user so...) I can solve it with( from: Crossthread operation not valid... - VB.NET):
listView1->CheckForIllegalCrossThreadCalls = false;
but since it is not good practice, I am looking for an alternative.
when I attempt to call this clr code in my thread:
void CClient::add(){
lvhandle = (HWND)project1::Form1::ClrForm1->listView1->Handle.ToPointer();
/* as you can see here, I tried to figure out how to use MethodInvoker but failed...
if(project1::Form1::ClrForm1->listView1->InvokeRequired){
lvhandle = (HWND)project1::Form1::ClrForm1->listView1->Handle.ToPointer();
//project1::Form1::ClrForm1->listView1->Invoke(gcnew System::Windows::Forms::MethodInvoker(this, &annoyme));
}
else
{
lvhandle = (HWND)project1::Form1::ClrForm1->listView1->Handle.ToPointer();
}*/
item.pszText = LPSTR_TEXTCALLBACK; // Sends an LVN_GETDISPINFO message.
item.mask = LVIF_TEXT | LVIF_IMAGE |LVIF_STATE;
item.stateMask = 0;
item.iSubItem = 0;
item.state = 0;
item.pszText = L"test";
item.lParam = 0;
ListView_InsertItem(lvhandle, &item);
std::string lol = std::to_string(item.iItem);
String^ test;
test = marshal_as<String^>(lol);
project1::Form1::ClrForm1->Text = test;
}
it gives me an exception:
Cross-thread operation not valid: Control 'Form1' accessed from a thread other than the thread it was created on.
ClrForm1 is defined as:
public ref class Form1 : public System::Windows::Forms::Form
{
public:
static Form1^ ClrForm1;
which I create when the entry point is triggered.
int main(array<System::String ^> ^args)
{
// Enabling Windows XP visual effects before any controls are created
Application::EnableVisualStyles();
Application::SetCompatibleTextRenderingDefault(false);
// Create the main window and run it
Form1::ClrForm1 = gcnew Form1();
Application::Run(Form1::ClrForm1);
return 0;
}
I also confirmed the error by doing:
project1::Form1::ClrForm1->Text = "Test!0";
hopefully I detailed this enough to get a response >.<