You need to access an instance object of your Form1 class - you can do something like this:
1. Add the following to your Form1 class definition - leaving label1 as a public field is usually not considered a good idea.
public:
void SetLabel1Text(String^ txt)
{
label1->Text = txt;
}
2. Access your new method through an instance reference to an object of type Form1
Form1^ mainForm = gcnew Form1();
mainForm->SetLabel1Text( L"Some text" );
Application::Run(mainForm);
private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e)
{
label1->Text = "10"; fnTest(); }
Update
This works like a charm (You should only have one message loop - Application::Run - in your program):
#include "stdafx.h"
#include "Form1.h"
using namespace SampleWinforms;
[STAThreadAttribute]
int main(array<System::String ^> ^args)
{
Application::EnableVisualStyles();
Application::SetCompatibleTextRenderingDefault(false);
Form1^ mainForm = gcnew Form1();
mainForm->label1->Text = L"Some Text";
Application::Run(mainForm);
return 0;
}
I've added a button "button1" and assigned the following event handler
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e)
{
Form1^ newForm = gcnew Form1();
newForm->label1->Text = L"Some Text On New Form";
newForm->Show();
}
This lets me create a new window and modify the label before showing it.
Update 2
To change the Text property of label1 on the current form:
private: System::Void button2_Click(System::Object^ sender, System::EventArgs^ e)
{
label1->Text = L"Some Text On the Current Form";
}
Assuming that there will only be a single instance of Form1, the following adds a static property
Instance
enabling you to write something like
Form::Instance->label1->Text = L"Simple singleton";
.
Since Form::Instance is static it will allow you to access the form, as long as it exists, from any code that includes the "form1.h"
public ref class Form1 : public System::Windows::Forms::Form
{
private:
typedef System::Windows::Forms::Form base;
static Form1^ instance;
public:
Form1(void)
{
InitializeComponent();
instance = this;
}
property static Form1^ Instance
{
Form1^ get()
{
return instance;
}
}
protected:
virtual void OnFormClosed(FormClosedEventArgs^ e) override
{
base::OnFormClosed(e);
instance = nullptr;
}
}
Regards
Espen Harlinn