Adding A Function To A Windows Form Button
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 7 of 7

Thread: Adding A Function To A Windows Form Button

  1. #1
    Join Date
    Jan 2012
    Posts
    11

    Smile Adding A Function To A Windows Form Button

    I understand the basic syntax functionality of C++,
    and I can write & compile simple C++ console apps (using Dev-C++).

    Now I plan on making simple windows form apps with Visual Studio,
    but I'm seeking help with integrating the auto generated managed code with my own functions.


    All I'm simply trying to do is add functions to buttons (on windows forms) using Visual C++ in Visual Studio.



    My objective is simply to draw a button on the form,
    double click on it to jump inside of the button's code,
    and add some code that will successfully compile & run.


    Like VB, I thought I could simply paste these basic C++ functions into the button1_click area:

    Code:
    private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) {
    	..I thought I could paste stuff in and done..
    	}
    With C++, I was thinking this would work..

    Code:
    private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) {
    		#include <iostream>
    		#include <fstream>
    		using namespace std;
    
    		int main()
    		{
    			ofstream outputFile;
    			outputFile.open("C:\\Users\\Anonymous\\Desktop\\Write2Me.txt");
    			outputFile << "Writes Line\n";
    			outputFile << "Writes Another Line\n";
    			outputFile.close();
    			return 0;
    		}
    	}
    Obviously, the above code is not even close. Not even in the same galaxy.

    My guess is I have to create a header file?, or a main.cpp file?, and link them somehow?

    I've searched several places online, read through a few books,
    and even watched 8 hours of VS Essentials Training over the past week.

    The self initiative is definitely there, but I'm stuck none the less.
    I almost paid Microsoft for online tech support 5 minutes ago (it's okay to laugh).

    Any kick start in the right direction is extremely appreciated.

    It's not so much this particular code I was trying-
    to use for this example (writing a simple .txt file),

    my question is more so where the #include headers go in general?,
    should my function be somewhere else?, how do I point to it?, link it?, or call it from the button1_click?

  2. #2
    Join Date
    Jun 2010
    Location
    Germany
    Posts
    2,583

    Re: Adding A Function To A Windows Form Button

    Quote Originally Posted by Alyssa Saila View Post

    My objective is simply to draw a button on the form,
    double click on it to jump inside of the button's code,
    and add some code that will successfully compile & run.
    You can do that, and it's not even difficult, as long as you do it right.

    Like VB, I thought I could simply paste these basic C++ functions into the button1_click area:

    Code:
    private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) {
    	..I thought I could paste stuff in and done..
    	}
    That's exactly how it works, but of course the code you paste must be valid. In particular it must be valid as a function body which means that it must not attempt to declare functions or include header files (among other things).

    With C++, I was thinking this would work..

    Code:
    private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) {
    		#include <iostream>
    		#include <fstream>
    		using namespace std;
    
    		int main()
    		{
    			ofstream outputFile;
    			outputFile.open("C:\\Users\\Anonymous\\Desktop\\Write2Me.txt");
    			outputFile << "Writes Line\n";
    			outputFile << "Writes Another Line\n";
    			outputFile.close();
    			return 0;
    		}
    	}
    Obviously, the above code is not even close. Not even in the same galaxy.
    That wouldn't even work in native C++. Function bodies aren't allowed to contain function declarations or header file inclusions there either. And while you actually can use native C++ constructs in C++/CLI to some extent, that is not recommended unless you have really good reasons to use them (which usually means you're doing managed/native interop) and particularly almost always unnecessary in beginner's programs.

    My guess is I have to create a header file?, or a main.cpp file?, and link them somehow?
    The empty function body the IDE sent you to to insert your code actually is in a header file that the IDE already has created for you. You may easily see that by having a look at the tab at the top of the code editor window. (The fact that the IDE tempts developers to place their entire form cass definitions in the header file is no good idea in general, and you should probably already know that and why if you know C++, since that's no different in native C++. But discussing how to do that the right way would probably be beyond the scope of this post for now.)

    I've searched several places online, read through a few books,
    and even watched 8 hours of VS Essentials Training over the past week.
    There are generally less online resources about C++/CLI compared to the other .NET languages. And I'd be somewhat surprised to find decent video tutorials about it (in particular from MS themselves).

    It's not so much this particular code I was trying-
    to use for this example (writing a simple .txt file),
    As a sample, FYI, the native code you attempted to paste into the button click handler above, translated into a valid C++/CLI console app, looks like this:

    Code:
    // Test24.cpp: Hauptprojektdatei.
    
    #include "stdafx.h"
    
    using namespace System;
    using namespace System::IO;
    
    int main(array<System::String ^> ^args)
    {
      StreamWriter ^outputFile;
      outputFile = File::CreateText("C:\\Users\\Anonymous\\Desktop\\Write2Me.txt");
      outputFile->WriteLine("Writes Line");
      outputFile->WriteLine("Writes Another Line");
      outputFile->Close();
      return 0;
    }
    my question is more so where the #include headers go in general?,
    should my function be somewhere else?
    That's not so different from native C++. I already mentioned the problem with the IDE always trying to place member function definitions in a form class' header file above. You may start reading about the specific problems of separating header and implementation files in C++/CLI in http://www.codeguru.com/forum/showthread.php?t=517519 and the links pointing further from there.

    how do I point to it?, link it?
    That has already been set up for you by the IDE.

    or call it from the button1_click?
    You'd just complete the click handler skeleton created for you by the IDE or, better yet, put the click handler implementation into a separate implementation file as described in the posts I linked to above. And of course you may freely call other functions from your click handler.

    Any kick start in the right direction is extremely appreciated.
    Well, frankly, C++/CLI is not quite for people who...

    [...] understand the basic syntax functionality of C++,
    and [...] can write & compile simple C++ console apps (using Dev-C++).
    If you want to write native C++ Windows GUI apps, I suggest you have a look at some of the free non-MS Windows GUI frameworks available. Posting an inquiry about that in the non-Visual C++ section will probably get you lots of opinions and recommendations about them. Microsoft's own flavor of native C++ Windows GUI framework, MFC, unfortunately is not part of the free VC++ Express Editions.

    If you want to go the .NET way, OTOH, I'd rather suggest C#, or perhaps VB .NET in case you already know something of that. Asking most of the developers around here you'll mostly hear recommendations against C++/CLI in favor of C#, in particular for beginners, since it would make their lives unnecessarily complicated. And while I, myself, usually advocate for C++/CLI, I tend to join their recommendations for now. Developers using C++/CLI must be aware that, despite the similar name, it is not just a C++ compliler for .NET; it rather is an entirely different language of its own. As to my experience, most beginners are not aware of this fact.

    However, of course you're welcome in the C++/CLI world as well if you're willing to take the challenge. But keep in mind the caveats above.
    I was thrown out of college for cheating on the metaphysics exam; I looked into the soul of the boy sitting next to me.

    This is a snakeskin jacket! And for me it's a symbol of my individuality, and my belief... in personal freedom.

  3. #3
    Join Date
    Jan 2012
    Posts
    11

    Re: Adding A Function To A Windows Form Button

    First and foremost I wanted to thank you for your time and analysis of my post.
    It was extermely sincerely appreciated you have no idea.

    Also, I wanted to personally confirm (which I'm sure is evident at this point)
    -that I am an "aspiring" programmer (with no real full knowledge of C++ yet).

    However, I did want to walk you through my thought process before asking you a very simple
    -yet extremely important question first..

    ..So.. ..explore the mind of another wannabe programmer with a keyboard

    I decided to learn programming to make windows apps.
    I needed to choose a language to learn.
    After a little reading, I was "lead to believe" C++ was in my best interest for the following reasons:

    -Most Universal (Used With Both Windows & Macs)
    -Most Used
    -Most Powerful & High-Level (Combo of Both)
    -Most Sought After By Employers From Applicants (What Employers Look For First)
    -C# Was "Just A Windows Side Thing" (Learn C++ First Is What I Read)
    -VB Was "Just A Windows Scripting Thing" (It's A Hobby Good To Know Type Language)
    -Java Was "Too Slow & Not As Professional" (Although This Was Just As Popular As C++??)
    -All Other Languages "Are Just Too Specific To Learn First"

    I enrolled in a C++ class working from the ground up.
    We mostly worked with console applications.
    As you well know, I didn't pick everything up (but I learned fair amount of syntax & object oriented logic).
    After I finished the class, "I thought I knew enough" to dive into Visual Studio.
    As originally desired, I wanted to make windows apps with fancy buttons & forms (not console apps).
    I knew in order to do this, I would need an IDE.
    I wanted the most universal and widely used powerful IDE.
    I chose Visual Studio for the same reasons I chose C++.
    After I installing it, I clicked new project to start my first app and saw this..

    http://www.iandmyself.me/NewProjectScrnShot.jpg

    My first thought was where is the plain regular standard C++ option at?

    I've been sad and confused since that day

    Now I know you're probably thinking.. what am I your developer therapist?

    I'm going back to drawing board to learn C++ a whole lot better before even attempting to open VS again,
    but before I do my question after this horrible chronological short story is..

    I want to be a successful developer..

    What language should I really be learning that would ensure it won't be a complete waste of time when:
    -I apply for a job (is there a universal standard expectation)?
    -Open IDE an find I'm going to have to relearn it a customize way the IDE wants me to?
    -Attempt To Crossover From A PC To A Mac? (Objective-C? --Which means lean C++ first right)?

    I'm really nervous that I'm going to get caught up in a proprietary spin cycle of useless information.

  4. #4
    Join Date
    Jun 2010
    Location
    Germany
    Posts
    2,583

    Re: Adding A Function To A Windows Form Button

    Quote Originally Posted by Alyssa Saila View Post
    First and foremost I wanted to thank you for your time and analysis of my post.
    It was extermely sincerely appreciated you have no idea.
    You're welcome!

    I decided to learn programming to make windows apps.
    I needed to choose a language to learn.
    After a little reading, I was "lead to believe" C++ was in my best interest for the following reasons:

    -Most Universal (Used With Both Windows & Macs)
    Correct. And it's used on many, many more platforms than just these two. But while the language is strictly standardized, the frameworks used to develop fancy apps are not. (More on that further throughout the post.)

    -Most Used
    Yes, it's quite popular, yet I wouldn't bet on that it actually (always) is on top of the heap. You might be surprised how popular Java actually is (I once have ssen it on #1 of the list in one survey) and .NET is catching up quickly. However, concluding "use C++/CLI" from "C++ is powerful and popular" and ".NET is becoming increasingly popular" is a misconception.

    -Most Powerful & High-Level (Combo of Both)
    Not even C++ is the magic bullet of programming languages. It can't be both what you claim it to be at the same time. However, it does offer a good balance between these two goals and allows you to fine-tune the balance in the sense that you can decide, over a comparatively wide range, to which of the two you want your code to tend. And of course you're not required to make that choice once and for all for your entire app. Instead you may set that fine-tuning differently for different parts of the app.

    -Most Sought After By Employers From Applicants (What Employers Look For First)
    I haven't seen current statistics about that for a while, but at least I wouldn't say it's valid (or at least accurate) to make such a general statement about that. These employers usualy won't look for one who knows C++ alone, but instead C++ in combination with certain frameworks and/or libraries. And there simply are too many of them to learn them all...

    -C# Was "Just A Windows Side Thing" (Learn C++ First Is What I Read)
    You'd be surprised to hear that .NET is not that strictly MS-bound. (Well, AFAIK it's not actually .NET but the CLI that has been publicly standardized, but the whole thing is more commonly referred to as .NET.) There are very well initiatives to implement it on non-MS platforms, like for instance the mono project, though I must admit that they're not yet of much practical relevance. (OTOH C++/CLI isn't of that much practical relevance either, neither compared to native C++ in general nor specifically in the .NET world.)

    -VB Was "Just A Windows Scripting Thing" (It's A Hobby Good To Know Type Language)
    Well, VB as a whole has been around for about two decades now, so there's a wide variety of things that are called "VB", and some of them actually may be considered sort of what you claim. (And there's a close relative called VBScript that definitly is a scripting language, no doubt.) But considering VB purely a "hobbyist's thing" is a misconception too. A good friend of mine is a guy who makes a good buck by doing database stuff in VBA and VB6 for big companies (and I mean really big - one of them, just for instance, is one of the major global players in telecommunication, in particular mobile telephony) as a freelancer. Note that he's not even using VB .NET which is much more powerful. And there's a bunch of those guys around.

    -Java Was "Too Slow & Not As Professional" (Although This Was Just As Popular As C++??)
    Java definitely is professional it can play out its advantages mostly when instant portability is desired and/or in server environments. However, my personal impression is that claims that it's slow are at least partially correct. Yet I do regularly use two Java apps of considerable complexity (one of them literally each day) and am overall comfortable with them.

    -All Other Languages "Are Just Too Specific To Learn First"
    There are highly specialized languages, though your list is far away from being just a half-way comprehensive list of general-purpose languages. And specialization isn't necessarily a disadvantage when it comes to learning. There even are languages that have been specifically designed to teach/learn programing like Pascal. It was by far not my first language but I learned structured programming with it, and it did a really good job in that. Its overall success was so big it even gained some relevance in the production area. The popular Delphi, for instance, is Pascal-based.

    After I finished the class, "I thought I knew enough" to dive into Visual Studio.
    This sort of misconception is rather common among beginners; not solely your own fault I'd say...

    As originally desired, I wanted to make windows apps with fancy buttons & forms (not console apps).
    If you want to make your apps fancy, I'd say it's easier to leave the pure MS path and check out some 3rd-party frameworks. (I don't intend to say it's particularly hard to write fancy apps with MS frameworks, you're just not quite that much MS-bound then.) IMO in particular the Microsoft framworks MFC and Windows Forms are specifically focused on writing apps orientated towards the traditional/"canonical" MS Windows look and feel. WPF, also from MS, OTOH is IMO a bit more oriented towards fanciness. [Pehaps a bit too many acronyms in that sentence... ] However, it's also .NET but practically can't be used with C++/CLI; the vastly dominant language for writing WPF apps is C#.

    I knew in order to do this, I would need an IDE.
    In theory no, in practice yes...

    I wanted the most universal and widely used powerful IDE.
    I chose Visual Studio for the same reasons I chose C++.
    Yes, Visual Studio is powerful and widely used. One of the consequences of this is that 3rd parties adapt their products to it. AFAIK, for instance, you can use it to write Qt-based C++ apps (and Qt is cross-platform).

    After I installing it, I clicked new project to start my first app and saw this..

    http://www.iandmyself.me/NewProjectScrnShot.jpg
    I was surprised to see that this is one of the full versions, no Express. That means you have MFC at your disposal, on #9 of the list, for writing Windows GUI apps, as well as its close relative ATL on #1. (Posts regarding these are best placed in the VC++ section.) So why C++/CLI?

    My first thought was where is the plain regular standard C++ option at?
    The "plain regular standard C++ option" is out of sight on the sceen shot and should be named Win32 Console Application. Now you know what and where it is, but you said you were out for something more fancy. You may already have learned that any sort of GUI programming is not covered at all by the C++ standard, like a vast lot of other things BTW. You'll often need to learn something in addition to C++ itself when writing serious C++ apps. (Strictly speaking, not even that std::cin and std::cout stuff is part of the core language, it's part of the standard library.)

    Now I know you're probably thinking.. what am I your developer therapist?
    Oooch... Sometimes people need just that. As long as you don't write posts like that each day you're welcome.

    What language should I really be learning that would ensure it won't be a complete waste of time when:
    -I apply for a job (is there a universal standard expectation)?
    -Open IDE an find I'm going to have to relearn it a customize way the IDE wants me to?
    -Attempt To Crossover From A PC To A Mac? (Objective-C? --Which means lean C++ first right)?
    The choice of language isn't always purely a matter of either personal preference or the environment(s) you're writing for. There often are other relevant factors or much more important factors. For instance, it's often dictated by your employer. (And usually that does not mean you learn it before you apply; you better already have learned it when you read the job offer. It simply takes too long to master a language of non-trivial complexity from almost scratch.)

    Mac OS is a Unix derivate, so sure you can write programs for it in C++. There are some Mac programmers around in the non-VC++ section to ask. AFAIK there even are come cross-platform frameworks that have Mac OS among their targets.

    As already suggested above in the context of job offers, it's not always you who makes the choice of languge. I, myself, have stopped counting the languages I ever learned and worked with at a count of 13 and that was about 17 years ago. Of course there have been added some more to the collection since then. And I don't think learning any of them realy was a waste of time and/or effort. (However, of course, I never actually used all of them actively at any given point in time.)

    Sometimes there are no options to choose from at all, for instance when writing Android apps, what I intend to start within the next months. This is done in Java. Period. So this is another one to add to my list, or else I'll have to forget about that project. (Well, actually there is another option to write Android apps in C, that I already know, but that's a niche technology with rather specific usefulness and usually not recommended. Somewhat like C++/CLI... And I wouldn't substantially gain anything by going that path against all the resistance anyway, just because I can use a language I know: I'd still need to learn the specific libraries involved.)
    Last edited by Eri523; January 10th, 2012 at 12:56 AM. Reason: Minor stylistic improvements and typos
    I was thrown out of college for cheating on the metaphysics exam; I looked into the soul of the boy sitting next to me.

    This is a snakeskin jacket! And for me it's a symbol of my individuality, and my belief... in personal freedom.

  5. #5
    Join Date
    Jan 2012
    Posts
    11

    Re: Adding A Function To A Windows Form Button

    I'm dizzy

    That was a euphoria of brilliant information you gave me.

    I had just a few more questions (which I'm preparing - they won't be long I promise).

    But first I simply have to clear up what I meant in regards to the "developer therapist" comment

    I was embarrassed after all that I had written & paranoid that you would think that I was crazy

    I was thinking to myself, man this guy is going to think I'm nuts at this point.

    So that's why I wrote that (I was thinking that you might've been thinking that about me)

    So it by no means was a shot at you, I was taking a joking jab at myself actually

    Thanks again for your help though, and for the record no one has helped me as much as you have.

  6. #6
    Join Date
    Jun 2010
    Location
    Germany
    Posts
    2,583

    Re: Adding A Function To A Windows Form Button

    Quote Originally Posted by Alyssa Saila View Post
    But first I simply have to clear up what I meant in regards to the "developer therapist" comment

    I was embarrassed after all that I had written & paranoid that you would think that I was crazy

    I was thinking to myself, man this guy is going to think I'm nuts at this point.

    So that's why I wrote that (I was thinking that you might've been thinking that about me)

    So it by no means was a shot at you, I was taking a joking jab at myself actually
    I can't see from what in my one-line response you got the impression that I felt offended. It's all fine.

    Actually, from a psychiatric point of view, I see much more indication of a potential problem in that burst of excuses of yours I quoted above than in your "therapist" one-liner from post #3 (or the entire post #3). [<- explicit sarcasm, IOW cynical joke - no offense intended]
    I was thrown out of college for cheating on the metaphysics exam; I looked into the soul of the boy sitting next to me.

    This is a snakeskin jacket! And for me it's a symbol of my individuality, and my belief... in personal freedom.

  7. #7
    Join Date
    Jan 2002
    Location
    Scaro, UK
    Posts
    5,940

    Re: Adding A Function To A Windows Form Button

    After a little reading, I was "lead to believe" C++ was in my best interest for the following reasons:

    -Most Universal (Used With Both Windows & Macs)
    -Most Used
    -Most Powerful & High-Level (Combo of Both)
    -Most Sought After By Employers From Applicants (What Employers Look For First)
    -C# Was "Just A Windows Side Thing" (Learn C++ First Is What I Read)
    -VB Was "Just A Windows Scripting Thing" (It's A Hobby Good To Know Type Language)
    -Java Was "Too Slow & Not As Professional" (Although This Was Just As Popular As C++??)
    -All Other Languages "Are Just Too Specific To Learn First"
    What you're doing isn't C++ - it's C++/CLI which is a completely different language although it looks very similar. Google for "native C++" and "managed C++" and see the differences.

    Some of your statements above aren't true. In my experience you'd be just as likely (if not more likely) to get a job doing C# than C++ (native C++ that is).

    If you're writing UI nobody these days commercially does this in C++/CLI. Use C# to write the UI, use C++/CLI (if necessary) to communicate to business logic written in native C++ (usually legacy code).

    And C# is definately NOT a windows side thing. It is from my experience one of the premier programming languages for Windows if not THE programming language for windows. Most jobs I see (and I'm a contractor) are for C# with C++ jobs reducing in number.

    And there's nothing wrong with specialising in Windows or Unix (lots more jobs for Windows development) - I do and have never had a problem.

    Darwen.
    Last edited by darwen; January 13th, 2012 at 05:47 AM.
    www.pinvoker.com - PInvoker - the .NET PInvoke Interface Exporter for C++ Dlls.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Azure Activities Information Page

Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center