Sampaio
Sampaio

Reputation: 367

Sharing data between console application and a windows form

I'm writing a program that works primarily in a console, but once in a while, I need to use forms.

I created a windows form and then switched the output to console. After that, I added one more form (Form2) to the project, and now I have code that looks something like this:

#include "stdafx.h"
#include <iostream> // For std::cout and such
#include "Form1.h"
#include "Form2.h"

using namespace testing_forms;

[STAThreadAttribute]
int main(array<System::String ^> ^args)
{
    // Enabling Windows XP visual effects before any controls are created
    Application::EnableVisualStyles();
    Application::SetCompatibleTextRenderingDefault(false); 


    /* Instructions Block 1 */

    Application::Run(gcnew Form1());

    /* Instructions Block 2 */

    Application::Run(gcnew Form2());

    /* Instructions Block 3 */

    return 0;
}

So, basically, the program runs the 1st Instruction Block, then calls a Form, then runs the 2nd Instruction Block, and so on.

However, this does not allow me to share data between the forms and the console, which, since it is only one program, I really need, such as usernames, integers and such.

The only way I can think of is keeping a text file and writing/reading to/from it from the console and the forms to share the information (I have not tested this), but, to be honest, I don't really like this solution.

So, how can I share data back and forth between a windows form and a console, using (preferably) only variables?

Upvotes: 1

Views: 651

Answers (1)

Geeky Guy
Geeky Guy

Reputation: 9379

There are many ways - you can use sockets, pipes, message queues, you can store information in a database, you can host a WCF service in the console application etc.

But I won't get into a discussion of which of those is best here. Really, if you are having this problem, then very probably you should make your whole solution a Windows Forms/WPF application. It's a lot easier to pass information between forms of the same application, specially if they can reference each other amongst themselves. They just have to call each other's methods, or access each other's properties, or go for the same static class. All in the same environment, no application boundaries crossed.

If you want to keep the console there, you could have the main form be hidden and open up a separate console app. Then you can feed this console with any relevant text.

Food for thought.

Upvotes: 1

Related Questions