通过另一个表单的按钮的单击事件更新表单中的状态栏的文本属性

时间:2015-06-19 07:02:58

标签: c++builder

您好我无法通过其他表单的按钮单击更新表单中状态栏的文本属性。它已成功编译并能够运行,直到我点击我得到的错误是“访问地址违规:XXXXXXXX .....”

使用Win 7中的C ++ Builder XE7。

Form1中:

#include "Main.h"
#include "minor.h"
....
TForm1 *Form1;
TForm2 *Form2;
....

Form2:

#include "minor.h"
#include "Main.h"
....
TForm2 *Form2;
TForm1 *Form1;
....
__fastcall TForm2::TForm2(TComponent* Owner)
: TForm(Owner)
{
TButton* btnTest2 = new TButton(this);
btnTest2->Height = 50;
btnTest2->Width = 200;
btnTest2->Left = 220;
btnTest2->Top = 50;
btnTest2->Caption = "Updated Statusbar Button";
btnTest2->Visible = true;
btnTest2->Enabled = true;
btnTest2->Parent = this;
btnTest2->OnClick = &ButtonClicked2; // Create your own event here manually!
}
//---------------------------------------------------------------------------

void __fastcall TForm2::ButtonClicked2(TObject *Sender)
{
Form1->statusbarMain->Panels->Items[0]->Text = "Hello2";   // PROBLEM!!!
}

知道为什么会遇到问题吗? 请指教..谢谢

1 个答案:

答案 0 :(得分:0)

您的Form2单元声明其自己的Form1变量与Form1单元中的Form1变量分开,并且第二个变量未初始化为任何有意义的变量。这就是您的代码崩溃的原因 - 您正在访问错误的Form1变量。

您需要删除Form2单元中的Form1变量和#include Form1的头文件(它应该已经为Form1&#39声明了extern ; s Form1变量)。这也是必要的,因为Form2需要TForm1类的完整声明才能访问其成员,例如statusbarMain

您在Form1单元中声明的Form2变量也是如此。您需要将其删除并改为使用#include "Form2.hpp"(应该有一个合适的extern声明)。

Form1.h:

...
class TForm1 : public TForm
{
__published:
    TStatusBar *statusbarMain;
    ...
};
extern TForm1 *Form1;
...

Form1.cpp:

#include "Main.h"
#include "minor.h"
#include "Form2.hpp" // <-- add this
....
TForm1 *Form1;
//TForm2 *Form2; // <-- get rid of this
....

Form2.h:

...
class TForm2 : public TForm
{
    ...
};
extern TForm2 *Form2;
...

Form2.cpp:

#include "minor.h"
#include "Main.h"
#include "Form1.hpp" // <-- add this
....
TForm2 *Form2;
//TForm1 *Form1; // <-- get rid of this
...
void __fastcall TForm2::ButtonClicked2(TObject *Sender)
{
    Form1->statusbarMain->Panels->Items[0]->Text = "Hello2";
}