Search code examples
c++-cli

Visual C++: Extracting event handler to .cpp file


As a php developer, after doing a lot of algorithmic c++ excercises I've decided to start learning Visual C++. Just after getting started I am stuck on something pretty basic. I am trying to extract Button-click event to my .cpp file from .h file.

My .h file:

#pragma once

namespace Project1 {
...
    this->button2->Click += gcnew System::EventHandler(this, &MyForm::button2_Click);
...
}

In my .cpp file I've tried to do so:

#include "MyForm.h"
using namespace System;
using namespace System::Windows::Forms;
namespace Project1 {
    [STAThread]
    void main(array<String^>^ args)
    {

        void MyForm::button2_Click(System::Object^  sender, System::EventArgs^  e) {
            // definition
        }
...
}

It does not work. It says that Project1::MyForm doesnt have button2_Click. What am I missing?


Solution

  • Standard 'learning the language' warning: This isn't C++ you're writing, it's C++/CLI. C++/CLI is a language from Microsoft intended to allow C# or other .Net languages to interface with standard C++. In that scenario, C++/CLI can provide the translation between the two. If you're still learning C++, please do not start with C++/CLI. In order to effectively write in C++/CLI, one should already know both C++ and C#, and then there's still things to learn about C++/CLI. If you want to learn C++, stick with standard (unmanaged) C++. (In Visual Studio, create a "Win32" C++ project.) If you want to learn managed code, then I would use C#.


    void main(array<String^>^ args)
    {
        void MyForm::button2_Click(System::Object^  sender, System::EventArgs^  e) {
            // definition
        }
    }
    

    That's not how you define methods: You've got the definition for one method inside the definition of another method, and that's not allowed.

    What you would need to do here is to declare the button2_Click method in MyForm.h, and have its implementation in MyForm.cpp

    // MyForm.h
    public ref class MyForm : System::Windows::Forms::Form
    {
        // Lots of other stuff...
    private:
        void button2_Click(System::Object^ sender, System::EventArgs^ e);
    }
    

    .

    // MyForm.cpp
    #include "MyForm.h"
    
    void MyForm::button2_Click(System::Object^ sender, System::EventArgs^ e)
    {
        // definition
    }