2016-11-15 3 views
0

Я работаю над проектом C++/CLI, и я новичок в нем. В моем проекте у меня есть 2 формы, одна главная, а другая - страница входа.метод события не называется

Я хочу иметь событие, которое, когда он успешно войдет в систему на странице входа, начнет получать некоторые изображения jpeg с сервера.

Я определил делегат, событие и метод для него, как показано ниже. Он полностью компилируется и запускается, но когда событие запускается, оно не запускает метод.

Я не нахожу ответа. Мне было интересно, можете ли вы мне помочь?

MainPage.h:

#pragma once 
#include "IPPort.h" 
#include "Login.h" 
#include "stdafx.h" 
#include "Utils.h" 


namespace UIv10 { 

using namespace System; 
using namespace System::ComponentModel; 
using namespace System::Collections; 
using namespace System::Windows::Forms; 
using namespace System::Data; 
using namespace System::Drawing; 

public ref class MainPage : public System::Windows::Forms::Form 
{ 
public: 
    MainPage(void) 
    { 
     InitializeComponent(); 
     Login^loginpage = gcnew Login(); 
     loginpage->JPEGgenerate += gcnew UIv10::Login::JPEGgeneratorEventHandler(this, &MainPage::OnJPEGgenerate); 
    } 

protected: 
    /// <summary> 
    /// Clean up any resources being used. 
    /// </summary> 
    ~MainPage() 
    { 
     if (components) 
     { 
      delete components; 
     } 
    } 
private: System::Windows::Forms::MenuStrip^ menuStrip1; 
private: System::Windows::Forms::ToolStripMenuItem^ fileToolStripMenuItem; 
private: System::Windows::Forms::ToolStripMenuItem^ connectToolStripMenuItem; 
private: System::Windows::Forms::ToolStrip^ toolStrip1; 
private: System::Windows::Forms::ToolStripButton^ toolStripButton1; 
private: System::Windows::Forms::PictureBox^ pictureBox1; 

private: 
    /// <summary> 
    /// Required designer variable. 
    /// </summary> 
    System::ComponentModel::Container ^components; 

#pragma region Windows Form Designer generated code 
    /// <summary> 
    /// Required method for Designer support - do not modify 
    /// the contents of this method with the code editor. 
    /// </summary> 
    void InitializeComponent(void) 
    { 
     System::ComponentModel::ComponentResourceManager^ resources = (gcnew System::ComponentModel::ComponentResourceManager(MainPage::typeid)); 
     this->menuStrip1 = (gcnew System::Windows::Forms::MenuStrip()); 
     this->fileToolStripMenuItem = (gcnew System::Windows::Forms::ToolStripMenuItem()); 
     this->connectToolStripMenuItem = (gcnew System::Windows::Forms::ToolStripMenuItem()); 
     this->toolStrip1 = (gcnew System::Windows::Forms::ToolStrip()); 
     this->toolStripButton1 = (gcnew System::Windows::Forms::ToolStripButton()); 
     this->pictureBox1 = (gcnew System::Windows::Forms::PictureBox()); 
     this->menuStrip1->SuspendLayout(); 
     this->toolStrip1->SuspendLayout(); 
     (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->pictureBox1))->BeginInit(); 
     this->SuspendLayout(); 

     // 
     // menuStrip1 
     // 
     this->menuStrip1->Items->AddRange(gcnew cli::array<System::Windows::Forms::ToolStripItem^>(1) { this->fileToolStripMenuItem }); 
     resources->ApplyResources(this->menuStrip1, L"menuStrip1"); 
     this->menuStrip1->Name = L"menuStrip1"; 
     // 
     // fileToolStripMenuItem 
     // 
     this->fileToolStripMenuItem->DropDownItems->AddRange(gcnew cli::array<System::Windows::Forms::ToolStripItem^>(1) { this->connectToolStripMenuItem }); 
     this->fileToolStripMenuItem->Name = L"fileToolStripMenuItem"; 
     resources->ApplyResources(this->fileToolStripMenuItem, L"fileToolStripMenuItem"); 
     // 
     // connectToolStripMenuItem 
     // 
     this->connectToolStripMenuItem->Name = L"connectToolStripMenuItem"; 
     resources->ApplyResources(this->connectToolStripMenuItem, L"connectToolStripMenuItem"); 
     this->connectToolStripMenuItem->Click += gcnew System::EventHandler(this, &MainPage::connectToolStripMenuItem_Click); 
     // 
     // toolStrip1 
     // 
     this->toolStrip1->Items->AddRange(gcnew cli::array<System::Windows::Forms::ToolStripItem^>(1) { this->toolStripButton1 }); 
     resources->ApplyResources(this->toolStrip1, L"toolStrip1"); 
     this->toolStrip1->Name = L"toolStrip1"; 
     // 
     // toolStripButton1 
     // 
     resources->ApplyResources(this->toolStripButton1, L"toolStripButton1"); 
     this->toolStripButton1->Name = L"toolStripButton1"; 
     this->toolStripButton1->Click += gcnew System::EventHandler(this, &MainPage::toolStripButton1_Click); 
     // 
     // pictureBox1 
     // 
     resources->ApplyResources(this->pictureBox1, L"pictureBox1"); 
     this->pictureBox1->Name = L"pictureBox1"; 
     this->pictureBox1->TabStop = false; 
     // 
     // MainPage 
     // 
     resources->ApplyResources(this, L"$this"); 
     this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font; 
     this->Controls->Add(this->pictureBox1); 
     this->Controls->Add(this->toolStrip1); 
     this->Controls->Add(this->menuStrip1); 
     this->MainMenuStrip = this->menuStrip1; 
     this->Name = L"MainPage"; 
     this->WindowState = System::Windows::Forms::FormWindowState::Maximized; 
     this->menuStrip1->ResumeLayout(false); 
     this->menuStrip1->PerformLayout(); 
     this->toolStrip1->ResumeLayout(false); 
     this->toolStrip1->PerformLayout(); 
     (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->pictureBox1))->EndInit(); 
     this->ResumeLayout(false); 
     this->PerformLayout(); 

    } 
#pragma endregion 

private: System::Void toolStripButton1_Click(System::Object^ sender, System::EventArgs^ e) { 
      IPPort^ipportpage = gcnew IPPort(); 
      ipportpage->Show(); 
} 
private: System::Void connectToolStripMenuItem_Click(System::Object^ sender, System::EventArgs^ e) { 
     /*IPPort^ipportpage = gcnew IPPort(); 
     ipportpage->Show();*/ 
     Login^ L = gcnew Login(); 
     L->Show(); 
} 

    void OnJPEGgenerate(System::Object^ sender,System::EventArgs^ e); 
}; 
} 


void UIv10::MainPage::OnJPEGgenerate(System::Object^ sender,System::EventArgs^ e) 
{ 
    MessageBoxA(NULL, "Failed to Login", "Attention", MB_OK); 
    throw gcnew System::NotImplementedException(); 
} 

Login.h:

#include <msclr/marshal.h> 
#include <Windows.h> 

#ifndef Login_h 
#define Login_h 

bool FLogin(char use[128], char pass[64]); 

#pragma once 

namespace UIv10 { 

    using namespace System; 
    using namespace System::ComponentModel; 
    using namespace System::Collections; 
    using namespace System::Windows::Forms; 
    using namespace System::Data; 
    using namespace System::Drawing; 



    public ref class Login : public System::Windows::Forms::Form 
    { 

    public: delegate void JPEGgeneratorEventHandler(System::Object^ sender, EventArgs^ e); 
    public: event JPEGgeneratorEventHandler^ JPEGgenerate; 
    public: 
     Login(void) 
     { 
      InitializeComponent(); 
      // 
      //TODO: Add the constructor code here 
      // 
     } 

    protected: 
     /// <summary> 
     /// Clean up any resources being used. 
     /// </summary> 
     ~Login() 
     { 
      if (components) 
      { 
       delete components; 
      } 
     } 
    private: System::Windows::Forms::Button^ btnCancel2; 
    private: System::Windows::Forms::Button^ btnLogin; 
    private: System::Windows::Forms::TextBox^ txtbPassword; 
    private: System::Windows::Forms::TextBox^ txtbUserName; 
    private: System::Windows::Forms::Label^ lblPassword; 
    private: System::Windows::Forms::Label^ lblUserName; 


    private: 
     /// <summary> 
     /// Required designer variable. 
     /// </summary> 
     System::ComponentModel::Container ^components; 

#pragma region Windows Form Designer generated code 
     /// <summary> 
     /// Required method for Designer support - do not modify 
     /// the contents of this method with the code editor. 
     /// </summary> 
     void InitializeComponent(void) 
     { 
      this->btnCancel2 = (gcnew System::Windows::Forms::Button()); 
      this->btnLogin = (gcnew System::Windows::Forms::Button()); 
      this->txtbPassword = (gcnew System::Windows::Forms::TextBox()); 
      this->txtbUserName = (gcnew System::Windows::Forms::TextBox()); 
      this->lblPassword = (gcnew System::Windows::Forms::Label()); 
      this->lblUserName = (gcnew System::Windows::Forms::Label()); 
      this->SuspendLayout(); 
      // 
      // btnCancel2 
      // 
      this->btnCancel2->Location = System::Drawing::Point(158, 174); 
      this->btnCancel2->Name = L"btnCancel2"; 
      this->btnCancel2->Size = System::Drawing::Size(71, 23); 
      this->btnCancel2->TabIndex = 11; 
      this->btnCancel2->Text = L"Cancel"; 
      this->btnCancel2->UseVisualStyleBackColor = true; 
      // 
      // btnLogin 
      // 
      this->btnLogin->Location = System::Drawing::Point(61, 174); 
      this->btnLogin->Name = L"btnLogin"; 
      this->btnLogin->Size = System::Drawing::Size(71, 23); 
      this->btnLogin->TabIndex = 10; 
      this->btnLogin->Text = L"Login"; 
      this->btnLogin->UseVisualStyleBackColor = true; 
      this->btnLogin->Click += gcnew System::EventHandler(this, &Login::btnLogin_Click); 
      // 
      // txtbPassword 
      // 
      this->txtbPassword->Location = System::Drawing::Point(112, 109); 
      this->txtbPassword->Name = L"txtbPassword"; 
      this->txtbPassword->PasswordChar = '*'; 
      this->txtbPassword->Size = System::Drawing::Size(126, 20); 
      this->txtbPassword->TabIndex = 9; 
      this->txtbPassword->Text = L"roseek"; 
      // 
      // txtbUserName 
      // 
      this->txtbUserName->Location = System::Drawing::Point(112, 65); 
      this->txtbUserName->Name = L"txtbUserName"; 
      this->txtbUserName->Size = System::Drawing::Size(126, 20); 
      this->txtbUserName->TabIndex = 8; 
      this->txtbUserName->Text = L"roseek"; 
      // 
      // lblPassword 
      // 
      this->lblPassword->Location = System::Drawing::Point(47, 117); 
      this->lblPassword->Name = L"lblPassword"; 
      this->lblPassword->Size = System::Drawing::Size(59, 12); 
      this->lblPassword->TabIndex = 7; 
      this->lblPassword->Text = L"Password"; 
      // 
      // lblUserName 
      // 
      this->lblUserName->AutoSize = true; 
      this->lblUserName->Location = System::Drawing::Point(47, 73); 
      this->lblUserName->Name = L"lblUserName"; 
      this->lblUserName->Size = System::Drawing::Size(60, 13); 
      this->lblUserName->TabIndex = 6; 
      this->lblUserName->Text = L"User Name"; 
      // 
      // Login 
      // 
      this->AutoScaleDimensions = System::Drawing::SizeF(6, 13); 
      this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font; 
      this->ClientSize = System::Drawing::Size(284, 262); 
      this->Controls->Add(this->btnCancel2); 
      this->Controls->Add(this->btnLogin); 
      this->Controls->Add(this->txtbPassword); 
      this->Controls->Add(this->txtbUserName); 
      this->Controls->Add(this->lblPassword); 
      this->Controls->Add(this->lblUserName); 
      this->Name = L"Login"; 
      this->Text = L"Login"; 
      this->ResumeLayout(false); 
      this->PerformLayout(); 

     } 
#pragma endregion 

    private: System::Void btnLogin_Click(System::Object^ sender, System::EventArgs^ e) { 
       String^username; 
       String^password; 

       username = this->txtbUserName->Text; 
       password = this->txtbPassword->Text; 

       using namespace System::Runtime::InteropServices; 
       IntPtr Cusername = Marshal::StringToHGlobalAnsi(username); 
       char* UserName = static_cast<char*>(Cusername.ToPointer()); 
       IntPtr Cpassword = Marshal::StringToHGlobalAnsi(password); 
       char* Password = static_cast<char*>(Cpassword.ToPointer()); 

       bool Lret = FLogin(UserName, Password); 
       if (Lret == TRUE) 
       { 
        JPEGgenerate(this,e); 
        this->Close(); 
       } 
       else 
       { 
        JPEGgenerate(this, e); 
        MessageBoxA(NULL, "Failed to Login", "Attention", MB_OK); 
        this->Close(); 
       } 
    } 
}; 
} 
#endif 

К сожалению для длинных кодов, я просто не знаю, где эта проблема может быть.

Проблема с электроприводом заключается в том, что когда JPEGgenerate (это, e); он запускает OnJPEGgenerate. Но это не так.

+1

Вы написали код, который компилируется, однако он не выглядит корректно. Вы создаете * два экземпляра класса Login, один раз в конструкторе MainPage, снова в функции connectToolStripMenuItem_Click(). Какой настоящий? Вы показываете только последний. Итак, это тот, чье событие вам нужно подписаться. –

ответ

0

Этот код кажется неправильным для меня:

MainPage(void) 
{ 
    InitializeComponent(); 
    Login^loginpage = gcnew Login(); 
    loginpage->JPEGgenerate += gcnew UIv10::Login::JPEGgeneratorEventHandler(this, &MainPage::OnJPEGgenerate); 
} 

Как я понял, вы должны иметь ссылку на такой объект, в противном случае, он будет удален (и присвоил обработчик не будет вызываться)

Другая часть (он не будет содержать регистрацию обработчика события)

Login^ L = gcnew Login(); 
L->Show(); 
+0

Благодарим вас за ответ. Итак, вы говорите, что обработчик не вызывает, потому что он уже удален? Как я могу это исправить? – Eoaneh

+0

Этот экземпляр 'loginpage' в конструкторе' MainPage' не используется *, вы можете его безопасно удалить. Добавьте обработчик событий в экземпляр 'L' в' connectToolStripMenuItem_Click' –

+0

@Eoaneh, вы должны попробовать исправить код после подсказки Lucas Trzesniewski – LmTinyToon

Смежные вопросы