1

我正在用 VS2012 C++ 制作一个 Windows 窗体应用程序。仅以情况为例,实际项目更复杂:我有一个包含 TextBox、Button 和 Timer 的表单。按钮只是触发计时器。定时器只是调用增加一些变量的函数。我需要在 TextBox 中显示递增的函数变量。

在 Form1.h 我添加代码:

    public: void Timer_Function(); //function activated by timer Tick
    void Set_Text(String ^str); //function to set TextBox Text
private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) 
         {
             if (timer1->Enabled == false)  timer1->Enabled = true;
             else   timer1->Enabled = false;
         }
private: System::Void timer1_Tick(System::Object^  sender, System::EventArgs^  e) 
         {
             Timer_Function();
         }

在这样的 My_app.cpp 代码中:

#include "stdafx.h"
#include "Form1.h"
#include "resource.h"

using namespace test_staticfunc;
[STAThreadAttribute]

int main(array<System::String ^> ^args)
{
Application::EnableVisualStyles();
Application::SetCompatibleTextRenderingDefault(false); 

Application::Run(gcnew Form1());
return 0;
}

void Form1::Timer_Function()
{
Timer_Func();
}

void Form1::Set_Text(String ^str)
{
textBox1->Text = str;
}

void Timer_Func()
{
static int I=0;
I++;

Form1::Set_Text(I.ToString());
}

函数 Timer_Func() 在“resource.h”中指定,如下所示:

void Timer_Func();

即,我试图通过将 Timer_Func() 的内部变量 I 传递给 Form1 公共方法 Set_Text() 来显示其当前状态。所以。这里的错误是 Set_Text() 不是静态方法。我试图将其设为静态,但收到错误“С2227:“->Text”左侧的操作数不是指向类、结构或联合的指针。” 如何正确处理?在那种情况下,静态方法正在尝试实现非静态方法,对吗?

或另一种方式:制作 Form1 的实例 - 而不是

Application::Run(gcnew Form1());

插入代码

Form1 ^My_form = gcnew Form1();
Application::Run(My_form);

并使用 Set_Text 作为类实例 My_form 的非静态方法。但 My_form 仅在 main() 中可用!我无法在其他任何地方制作 My_form。有没有办法让它全球化或什么?

可能有其他方法可以解决这个问题吗?

请帮忙!我已经搜索了几个论坛的答案,但没有找到答案。更准确地说,他们都不适合。PS对不起我的英语不好!^_^

4

0 回答 0