Search code examples
.netwinformstextboxc++-clitextchanged

WinForms C++ How to detect that text has changed since it was saved last time?


I'm working on Notepad using Windows Forms and C++. Now I'm trying to set up the TextChanged event, so the program should not ask the user if he wants to save his document if there will be no changes to save (before closing the application).

When I was working on OnClosing method, it was like:

    protected: virtual void OnClosing(CancelEventArgs^ e) override 
    { // code here }

But TextChanged is not a method, it's an event.

The documentation says I can use this:

    public:
    event TextChangedEventHandler^ TextChanged { // code here } 

But my Visual Studio says that TextChangedEventHandler is undefined.

Is there any way to detect that the text has changed since it was saved last time? My only idea is to create a new string variable; the program will save text to the variable everytime it will be saved in a file. At the end, the application will check if the text in the TextBox and the variable is the same, but I'm afraid it can slow down the application.

I will appreciate any help.


Solution

  • Firstly I've set up the variable:

    private: bool TextChanged = false;
    

    By clicking on the Textbox and Properties we can find a TextChanged event. Clicking twice we're adding a code to our .h file and then we should mark what should happen when the text is changing, in this case:

    private: System::Void tresc_TextChanged(System::Object^  sender, 
        System::EventArgs^  e) 
            {
                TextChanged = true;
            }
    

    At the end, I added

    TextChanged = false;
    

    in every single method where I needed to, like i.e. saving or opening a new file.