CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 10 of 10
  1. #1
    Join Date
    Sep 2011
    Posts
    10

    [RESOLVED] C++ CLI Form Problems - Label Display

    My overall goal is to create a program to read the mouse position on a form and control a servo motor attached to the program based on the mouse position. However, I am coming across an issue (or several) in the creation of the form and reading mouse position. I initially wrote the program using C++ console application to read to mouse position (since I am fairly new to Visual C++), which worked fine. Now I am trying to convert the program into something I can use with a form as I previously described. No errors occur and the form renders without an issue, however, no matter how long I have tried I can't get the label to display the coordinate position of the mouse. After thinking it might be an issue with my variables, I tried to just display anything into the label, and nothing happens.

    MAIN FILE
    Code:
    // MouseDynamixel.cpp : main project file.
    
    #include "stdafx.h"
    #include "Form1.h"
    #include <stdio.h>
    #include "windows.h"
    #include <conio.h>
    #include <iostream>
    
    using namespace std;
    using namespace MouseDynamixel;
    
    
    int main(array<System::String ^> ^args)
    {
    	// Enabling Windows XP visual effects before any controls are created
    	Application::EnableVisualStyles();
    	Application::SetCompatibleTextRenderingDefault(false); 
    
    	// Create the main window and run it
    	Application::Run(gcnew Form1());
    	return 0;
    
    	//::MessageBoxA(0, "Error", "Warning", MB_OK);
    
    	Label ^ lblMouseX = gcnew Label;
    	Label ^ lblMouseY;
    
    	//get the position of cursor first
    	POINT pos;
    	GetCursorPos(&pos);
    	int x=pos.x;
    	int y=pos.y;
    
    	//lblMouseX->Text = String::Format("L",x,y);
    	//::MessageBoxA(0, "Error", "Warning", MB_OK);
    	lblMouseX->Text = "Hi";
    	//lblMouseX->Text= Convert::ToString(x);
    	lblMouseY->Text= Convert::ToString(y);	
    }
    Form1.h
    Code:
    #pragma once
    
    
    namespace MouseDynamixel {
    
    	using namespace System;
    	using namespace System::ComponentModel;
    	using namespace System::Collections;
    	using namespace System::Windows::Forms;
    	using namespace System::Data;
    	using namespace System::Drawing;
    
    	/// <summary>
    	/// Summary for Form1
    	///
    	/// WARNING: If you change the name of this class, you will need to change the
    	///          'Resource File Name' property for the managed resource compiler tool
    	///          associated with all .resx files this class depends on.  Otherwise,
    	///          the designers will not be able to interact properly with localized
    	///          resources associated with this form.
    	/// </summary>
    	public ref class Form1 : public System::Windows::Forms::Form
    	{
    	public:
    		Form1(void)
    		{
    			InitializeComponent();
    			//
    			//TODO: Add the constructor code here
    			//
    		}
    
    	protected:
    		/// <summary>
    		/// Clean up any resources being used.
    		/// </summary>
    		~Form1()
    		{
    			if (components)
    			{
    				delete components;
    			}
    		}
    	public: System::Windows::Forms::Label^  lblMouseX;
    	protected: 
    
    	protected: 
    
    	protected: 
    
    
    	private: System::Windows::Forms::PictureBox^  pictureBox1;
    	private: System::Windows::Forms::Label^  label1;
    	private: System::Windows::Forms::Label^  label2;
    	public: System::Windows::Forms::Label^  lblMouseY;
    	private: 
    	private: System::Windows::Forms::Label^  label3;
    	public: 
    	public: 
    
    	public: 
    	private: 
    
    
    
    	protected: 
    
    	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(Form1::typeid));
    		this->lblMouseX = (gcnew System::Windows::Forms::Label());
    		this->pictureBox1 = (gcnew System::Windows::Forms::PictureBox());
    		this->label1 = (gcnew System::Windows::Forms::Label());
    		this->label2 = (gcnew System::Windows::Forms::Label());
    		this->lblMouseY = (gcnew System::Windows::Forms::Label());
    		this->label3 = (gcnew System::Windows::Forms::Label());
    		(cli::safe_cast<System::ComponentModel::ISupportInitialize^  >(this->pictureBox1))->BeginInit();
    		this->SuspendLayout();
    		// 
    		// lblMouseX
    		// 
    		this->lblMouseX->BackColor = System::Drawing::SystemColors::ControlLight;
    		this->lblMouseX->BorderStyle = System::Windows::Forms::BorderStyle::FixedSingle;
    		this->lblMouseX->Location = System::Drawing::Point(135, 240);
    		this->lblMouseX->Name = L"lblMouseX";
    		this->lblMouseX->Size = System::Drawing::Size(35, 24);
    		this->lblMouseX->TabIndex = 1;
    		this->lblMouseX->TextAlign = System::Drawing::ContentAlignment::MiddleCenter;
    		// 
    		// pictureBox1
    		// 
    		this->pictureBox1->Image = (cli::safe_cast<System::Drawing::Image^  >(resources->GetObject(L"pictureBox1.Image")));
    		this->pictureBox1->InitialImage = (cli::safe_cast<System::Drawing::Image^  >(resources->GetObject(L"pictureBox1.InitialImage")));
    		this->pictureBox1->Location = System::Drawing::Point(36, 12);
    		this->pictureBox1->Name = L"pictureBox1";
    		this->pictureBox1->Size = System::Drawing::Size(224, 225);
    		this->pictureBox1->TabIndex = 0;
    		this->pictureBox1->TabStop = false;
    		this->pictureBox1->WaitOnLoad = true;
    		this->pictureBox1->Click += gcnew System::EventHandler(this, &Form1::pictureBox1_Click);
    		// 
    		// label1
    		// 
    		this->label1->AutoSize = true;
    		this->label1->Location = System::Drawing::Point(12, 246);
    		this->label1->Name = L"label1";
    		this->label1->Size = System::Drawing::Size(81, 13);
    		this->label1->TabIndex = 2;
    		this->label1->Text = L"Current Position";
    		// 
    		// label2
    		// 
    		this->label2->AutoSize = true;
    		this->label2->Location = System::Drawing::Point(111, 246);
    		this->label2->Name = L"label2";
    		this->label2->Size = System::Drawing::Size(17, 13);
    		this->label2->TabIndex = 3;
    		this->label2->Text = L"X:";
    		// 
    		// lblMouseY
    		// 
    		this->lblMouseY->BackColor = System::Drawing::SystemColors::ControlLight;
    		this->lblMouseY->BorderStyle = System::Windows::Forms::BorderStyle::FixedSingle;
    		this->lblMouseY->Location = System::Drawing::Point(234, 240);
    		this->lblMouseY->Name = L"lblMouseY";
    		this->lblMouseY->Size = System::Drawing::Size(35, 24);
    		this->lblMouseY->TabIndex = 4;
    		this->lblMouseY->TextAlign = System::Drawing::ContentAlignment::MiddleCenter;
    		// 
    		// label3
    		// 
    		this->label3->AutoSize = true;
    		this->label3->Location = System::Drawing::Point(199, 246);
    		this->label3->Name = L"label3";
    		this->label3->Size = System::Drawing::Size(17, 13);
    		this->label3->TabIndex = 5;
    		this->label3->Text = L"Y:";
    		// 
    		// Form1
    		// 
    		this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
    		this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
    		this->ClientSize = System::Drawing::Size(292, 266);
    		this->Controls->Add(this->label3);
    		this->Controls->Add(this->lblMouseY);
    		this->Controls->Add(this->label2);
    		this->Controls->Add(this->label1);
    		this->Controls->Add(this->lblMouseX);
    		this->Controls->Add(this->pictureBox1);
    		this->ForeColor = System::Drawing::SystemColors::ControlText;
    		this->Name = L"Form1";
    		this->Text = L"Form1";
    		(cli::safe_cast<System::ComponentModel::ISupportInitialize^  >(this->pictureBox1))->EndInit();
    		this->ResumeLayout(false);
    		this->PerformLayout();
    
    			}
    #pragma endregion
    	private: System::Void pictureBox1_Click(System::Object^  sender, System::EventArgs^  e) {
    				 }
    		};
    }
    As you can see in the main program, I have tried many ways to do things, based on advice I saw on other posts, but nothing has worked. I am sure I am probably just missing some simple error, however, I cannot find it. Any advice to help me out would be greatly appreciate. The labels I am trying to display the text in are lblMouseX (for X coordinate) and lblMouseY (for Y coordinate).

    Thanks

    Note: Some parts of my code that I thought might be useful are commented out.

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

    Re: C++ CLI Form Problems - Label Display

    Quote Originally Posted by SpartanGuy07 View Post
    I am sure I am probably just missing some simple error [...].
    That's what one might call it...

    Code:
    // MouseDynamixel.cpp : main project file.
    
    #include "stdafx.h"
    #include "Form1.h"
    #include <stdio.h>
    #include "windows.h"
    #include <conio.h>
    #include <iostream>
    
    using namespace std;
    using namespace MouseDynamixel;
    
    
    int main(array<System::String ^> ^args)
    {
    	// Enabling Windows XP visual effects before any controls are created
    	Application::EnableVisualStyles();
    	Application::SetCompatibleTextRenderingDefault(false); 
    
    	// Create the main window and run it
    	Application::Run(gcnew Form1());
    	return 0;
    
    	//::MessageBoxA(0, "Error", "Warning", MB_OK);
    
    	Label ^ lblMouseX = gcnew Label;
    	Label ^ lblMouseY;
    
    	//get the position of cursor first
    	POINT pos;
    	GetCursorPos(&pos);
    	int x=pos.x;
    	int y=pos.y;
    
    	//lblMouseX->Text = String::Format("L",x,y);
    	//::MessageBoxA(0, "Error", "Warning", MB_OK);
    	lblMouseX->Text = "Hi";
    	//lblMouseX->Text= Convert::ToString(x);
    	lblMouseY->Text= Convert::ToString(y);	
    }
    The code highlighted in red will never, never, never get executed because it's after an unconditional return statement, highlighted in green, which exits the main() function and thus ends the whole program. Even if you'd move the code to before the return: The call to Application::Run() that precedes the return does not return before the main form (the Form1 instance) gets closed.

    And that's not all: One of your label variables isn't even assigned a valid label instance ever at all, and the other label is "nowhere", in particular not on your main form. Controls are usually placed on a form using the Forms Designer, in particular in beginner's programs. Even advanced programmers rarely have the need to create controls "out of the blue".

    Generally, there rarely is a need to touch the main() function of a Windows Forms application at all. I, personally, after having written dozens of Windows Forms programs (some of which are rather advanced), have modified that function perhaps two or three times, including experimental test programs.

    In addition, you're mixing C++/CLI stuff with native C++ stuff in your code which should be avoided unless one has really good reasons to do so (and I see none of those here).

    The usually correct way of doing what you describe is to create a handler for the MouseMove event of your form, which can be easily done with the Forms Designer, and update your labels (which of course have been placed on the form the conventional way using the Forms Designer) from there. You'll find the mouse coordinates among the properties of the object passed to your handler as the e parameter.

    In case it's not sufficient to only get notified about mouse moves while the mouse is over your form, you can either capture the mouse or poll the mouse position using the form's MousePosition property in a Timer Tick event handler. Which one of these options is more appropriate probably depends on the overall system environment your program is supposed to run in, that I don't know.

    Ah, and... Welcome to CodeGuru!
    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
    Sep 2011
    Posts
    10

    Re: C++ CLI Form Problems - Label Display

    Quote Originally Posted by Eri523 View Post
    That's what one might call it...
    i knew it...

    Quote Originally Posted by Eri523 View Post
    Generally, there rarely is a need to touch the main() function of a Windows Forms application at all. I, personally, after having written dozens of Windows Forms programs (some of which are rather advanced), have modified that function perhaps two or three times, including experimental test programs.

    In addition, you're mixing C++/CLI stuff with native C++ stuff in your code which should be avoided unless one has really good reasons to do so (and I see none of those here).
    Like I mentioned, this is really my first C++/CLI program. I have programmed using Visual Basic (about 8 years ago) and I took C++ programming classes (4 years ago), so I was hoping that I could quickly relearn and then use C++/CLI for some things.

    Quote Originally Posted by Eri523 View Post
    The usually correct way of doing what you describe is to create a handler for the MouseMove event of your form, which can be easily done with the Forms Designer, and update your labels (which of course have been placed on the form the conventional way using the Forms Designer) from there. You'll find the mouse coordinates among the properties of the object passed to your handler as the e parameter.

    In case it's not sufficient to only get notified about mouse moves while the mouse is over your form, you can either capture the mouse or poll the mouse position using the form's MousePosition property in a Timer Tick event handler. Which one of these options is more appropriate probably depends on the overall system environment your program is supposed to run in, that I don't know.
    My original thought for this program was to have a set space, with an image of a circle, where going around the circle would coincide with the movement of the servo motor (when the position around the circle is clicked). Therefore observing the space over the form is definitely sufficient.

    So now my question is, if you know, where I would add the code that would be responsible for sending the messages to the servo based on the form's response. Would that still be in the MouseEvent::Form1 code? (The program I used to control the servo as a test was previously written in C++, so I am hoping there won't be too much of an issue converting that code either.)

    Quote Originally Posted by Eri523 View Post
    Ah, and... Welcome to CodeGuru!
    Thanks! I appreciate your help!

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

    Re: C++ CLI Form Problems - Label Display

    Quote Originally Posted by SpartanGuy07 View Post
    My original thought for this program was to have a set space, with an image of a circle, where going around the circle would coincide with the movement of the servo motor (when the position around the circle is clicked). Therefore observing the space over the form is definitely sufficient.
    For that purpose you don't even need to observe mouse movement. Since this is, you probably figure, something programmers want to do really often, there's the MouseClick event for that purpose. It's much like the MouseMove event, just that it's only fired when the user clicks. (There also is a Click event but that doesn't get passed the coordinates of the click and thus isn't suitÃ*ble for your purpose.)

    So now my question is, if you know, where I would add the code that would be responsible for sending the messages to the servo based on the form's response. Would that still be in the MouseEvent::Form1 code? (The program I used to control the servo as a test was previously written in C++, so I am hoping there won't be too much of an issue converting that code either.)
    Well, .NET isn't really the perfect environment for direct hardware control. How did you control the hardware in your C++ code? In case that can't simply be done from manged code, C++/CLI can play its trump card that, among the .NET languages, it's the one that most easily can integrate native code. In a pinch you can even simply implant one or more of your existing native functions into the C++/CLI project and call them from the managed code. But, as already mentioned, that should only be done if really needed.

    And to answer the primary question in your paragraph above: It may not be good design to have all the hardware control code inside the event handler function, but yes, in effect the hardware control is initiated from there, perhaps by calling other functions.

    Thanks! I appreciate your help!
    You're welcome!
    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
    Sep 2011
    Posts
    10

    Re: C++ CLI Form Problems - Label Display

    I'm not really sure that I understand how to use the event to read and report the mouse position. Clarification on this would be greatly appreciated.

    Sorry, but I am really new at this and I am getting this error "Error C2143: Syntax error : missing ';' before 'public' " and "Error C3708:'MouseEventHandler': improper use of 'event';must be made a member of compatible event source."
    Last edited by SpartanGuy07; September 9th, 2011 at 11:35 AM.

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

    Re: C++ CLI Form Problems - Label Display

    Quote Originally Posted by SpartanGuy07 View Post
    I'm not really sure that I understand how to use the event to read and report the mouse position.
    The second parameter to your event handler, when it gets invoked by the framework, is a MouseEventArgs object. At least when the event handler's function header has been created by the IDE, that parameter will be named e. From that object you can, among other information, obtain the coordinates the mouse click occurred at as e->Location.

    Sorry, but I am really new at this and I am getting this error "Error C2143: Syntax error : missing ';' before 'public' " and "Error C3708:'MouseEventHandler': improper use of 'event';must be made a member of compatible event source."
    Sorry, without seeing your code I can't tell what this has been caused by. I need not only the entire event handler function but also some lines before and after that. Did you create the event handler with the IDE?
    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
    Sep 2011
    Posts
    10

    Talking Re: C++ CLI Form Problems - Label Display

    Alright, using some code from one of the examples you gave me I created a program with a form that is formatted basically the way I need it. It recognizes when the mouse is in the set area (and when it leaves) and can create lines based on the path the mouse point traveled since the last click.

    Code:
    #pragma once
    #using <System.dll>
    #using <System.Windows.Forms.dll>
    #using <System.Drawing.dll>
    
    	using namespace System;
    	using namespace System::ComponentModel;
    	using namespace System::Collections;
    	using namespace System::Windows::Forms;
    	using namespace System::Data;
    	using namespace System::Drawing;
    
    namespace MouseEvent
    {
       public ref class Form1: public System::Windows::Forms::Form
       {
       private:
          System::Windows::Forms::Panel^ panel1;
          System::Windows::Forms::Label ^ label1;
    	  System::Windows::Forms::Label ^ lblMouseXY;
    	  System::Windows::Forms::Label ^ lblCurrentPos;
          System::Windows::Forms::Button^ clearButton;
          System::Drawing::Drawing2D::GraphicsPath^ mousePath;
          System::Windows::Forms::GroupBox^ infoBox1;
          int fontSize;
    
       public:
          Form1()
          {
             fontSize = 20;
             mousePath = gcnew System::Drawing::Drawing2D::GraphicsPath;
             this->panel1 = gcnew System::Windows::Forms::Panel;
             this->label1 = gcnew System::Windows::Forms::Label;
    		 this->lblCurrentPos = gcnew System::Windows::Forms::Label;
    		 this->lblMouseXY = gcnew System::Windows::Forms::Label;
             this->clearButton = gcnew System::Windows::Forms::Button;
             this->infoBox1 = gcnew System::Windows::Forms::GroupBox;
    
             // Mouse Events Label
             this->label1->Location = System::Drawing::Point( 15, 80);
             this->label1->Size = System::Drawing::Size( 100, 23 );
    
    		 //Position Label
    		 this->lblCurrentPos->AutoSize = true;
             this->lblCurrentPos->Location = System::Drawing::Point( 15, 35 );
             this->lblCurrentPos->Size = System::Drawing::Size( 35, 13 );
    		 this->lblCurrentPos->Text = "Current Mouse Position: ";
    
    		 //XY Label
    		 this->lblMouseXY->AutoSize = true;
    		 this->lblMouseXY->Location = System::Drawing::Point( 25, 55 );
             this->lblMouseXY->Size = System::Drawing::Size( 35, 13 );
    		 this->lblMouseXY->Text = "XY Here";
    
             // Mouse Panel
             this->panel1->Anchor = static_cast<System::Windows::Forms::AnchorStyles>(System::Windows::Forms::AnchorStyles::Top | System::Windows::Forms::AnchorStyles::Left | System::Windows::Forms::AnchorStyles::Right);
             this->panel1->BackColor = System::Drawing::SystemColors::ControlDark;
             this->panel1->Location = System::Drawing::Point( 10, 120 );
             this->panel1->Size = System::Drawing::Size( 280, 170 );
             this->panel1->MouseUp += gcnew System::Windows::Forms::MouseEventHandler( this, &Form1::panel1_MouseUp );
             this->panel1->Paint += gcnew System::Windows::Forms::PaintEventHandler( this, &Form1::panel1_Paint );
             this->panel1->MouseEnter += gcnew System::EventHandler( this, &Form1::panel1_MouseEnter );
             this->panel1->MouseHover += gcnew System::EventHandler( this, &Form1::panel1_MouseHover );
             this->panel1->MouseMove += gcnew System::Windows::Forms::MouseEventHandler( this, &Form1::panel1_MouseMove );
             this->panel1->MouseLeave += gcnew System::EventHandler( this, &Form1::panel1_MouseLeave );
             this->panel1->MouseDown += gcnew System::Windows::Forms::MouseEventHandler( this, &Form1::panel1_MouseDown );
    
             // Clear Button
             this->clearButton->Anchor = static_cast<System::Windows::Forms::AnchorStyles>(System::Windows::Forms::AnchorStyles::Top | System::Windows::Forms::AnchorStyles::Right);
             this->clearButton->Location = System::Drawing::Point( 210, 90 );
             this->clearButton->TabIndex = 1;
             this->clearButton->Text = "Clear";
             this->clearButton->Click += gcnew System::EventHandler( this, &Form1::clearButton_Click );
    
             // InfoBox
             this->infoBox1->Anchor = static_cast<System::Windows::Forms::AnchorStyles>(System::Windows::Forms::AnchorStyles::Top | System::Windows::Forms::AnchorStyles::Left | System::Windows::Forms::AnchorStyles::Right);
             this->infoBox1->Location = System::Drawing::Point( 8, 15 );
             this->infoBox1->Size = System::Drawing::Size( 150, 100 );
             this->infoBox1->Text = "Mouse Information";
    
             // Set up how the form should be displayed and add the controls to the form.
             this->ClientSize = System::Drawing::Size( 300, 300 );
             array<System::Windows::Forms::Control^>^temp0 = {this->lblMouseXY,this->lblCurrentPos,this->clearButton,this->panel1,this->label1,this->infoBox1};
             this->Controls->AddRange( temp0 );
             this->Text = "Dynamixel Mouse Control";
          }
    
       private:
          void panel1_MouseDown( Object^ /*sender*/, System::Windows::Forms::MouseEventArgs^ e )
          {
             // Update the mouse path with the mouse information
             Point mouseDownLocation = Point(e->X,e->Y);
             String^ eventString = nullptr;
             switch ( e->Button )
             {
                case ::MouseButtons::Left:
                   eventString = "L";
                   break;
    
                case ::MouseButtons::Right:
                   eventString = "R";
                   break;
    
                case ::MouseButtons::Middle:
                   eventString = "M";
                   break;
    
                case ::MouseButtons::XButton1:
                   eventString = "X1";
                   break;
    
                case ::MouseButtons::XButton2:
                   eventString = "X2";
                   break;
    
                case ::MouseButtons::None:
                default:
                   break;
             }
             if ( eventString != nullptr )
             {
                mousePath->AddString( eventString, FontFamily::GenericSerif, (int)FontStyle::Bold, (float)fontSize, mouseDownLocation, StringFormat::GenericDefault );
             }
             else
             {
                mousePath->AddLine( mouseDownLocation, mouseDownLocation );
             }
    
             panel1->Focus();
             panel1->Invalidate();
          }
    
          void panel1_MouseEnter( Object^ sender, System::EventArgs^ /*e*/ )
          {
    
             // Update the mouse event label to indicate the MouseEnter event occurred.
             label1->Text = String::Concat( "Mouse Entered" );
          }
    
          void panel1_MouseHover( Object^ sender, System::EventArgs^ /*e*/ )
          {
    
             // Update the mouse event label to indicate the MouseHover event occurred.
             label1->Text = String::Concat( "Mouse Hovering" );
          }
    
          void panel1_MouseLeave( Object^ sender, System::EventArgs^ /*e*/ )
          {
    
             // Update the mouse event label to indicate the MouseLeave event occurred.
             label1->Text = String::Concat( "Mouse Left" );
          }
    
          void panel1_MouseMove( Object^ /*sender*/, System::Windows::Forms::MouseEventArgs^ e )
          {
             // Update the mouse path that is drawn onto the Panel.
             int mouseX = e->X;
             int mouseY = e->Y;
             mousePath->AddLine( mouseX, mouseY, mouseX, mouseY );
          }
    
          void panel1_MouseWheel( Object^ /*sender*/, System::Windows::Forms::MouseEventArgs^ e )
          {
             // Update the drawing based upon the mouse wheel scrolling.
             int numberOfTextLinesToMove = e->Delta * SystemInformation::MouseWheelScrollLines / 120;
             int numberOfPixelsToMove = numberOfTextLinesToMove * fontSize;
             if ( numberOfPixelsToMove != 0 )
             {
                System::Drawing::Drawing2D::Matrix^ translateMatrix = gcnew System::Drawing::Drawing2D::Matrix;
                translateMatrix->Translate( 0, (float)numberOfPixelsToMove );
                mousePath->Transform(translateMatrix);
             }
    
             panel1->Invalidate();
          }
    
          void panel1_MouseUp( Object^ /*sender*/, System::Windows::Forms::MouseEventArgs^ e )
          {
             Point mouseUpLocation = System::Drawing::Point( e->X, e->Y );
    
             // Show the number of clicks in the path graphic.
             int numberOfClicks = e->Clicks;
             mousePath->AddString( String::Format( "   {0}", numberOfClicks ), FontFamily::GenericSerif, (int)FontStyle::Bold, (float)fontSize, mouseUpLocation, StringFormat::GenericDefault );
             panel1->Invalidate();
          }
    
          void panel1_Paint( Object^ /*sender*/, System::Windows::Forms::PaintEventArgs^ e )
          {
             // Perform the painting of the Panel.
             e->Graphics->DrawPath( System::Drawing::Pens::DarkRed, mousePath );
          }
    
          void clearButton_Click( Object^ /*sender*/, System::EventArgs^ /*e*/ )
          {
             // Clear the Panel display.
             delete mousePath;
             mousePath = gcnew System::Drawing::Drawing2D::GraphicsPath;
             panel1->Invalidate();
          }
       };
    }
    I think my confusion comes with the fact that I don't really understand how the event is actually created and utilized. If it is simple enough could you show me how you would create the event that can report the coordinates to the lblMouseXY ? If not, just please point me in the right direction again.

    I think after exactly how events work I will be pretty well set with C++/CLI! (I hope haha)

  8. #8
    Join Date
    Jun 2010
    Location
    Germany
    Posts
    2,675

    Re: C++ CLI Form Problems - Label Display

    Your question about events sounds a bit general. Does this help: How to: Consume Events in a Windows Forms Application? What the article does not explain is how to create an event handler with the Designer, but that's not too complicated: Simply select the control (herer: the form) you want to create an event handler for in the Designer and then double-click on the empty entry for the desired event in the events list in the control's property window. You'll probably need to first switch from the property list to the list of events by clicking the button with the lightning symbol.

    An event handler that displays the mouse coordinates in a label (in this case on mouse move) is quite unspectacular:

    Code:
    System::Void Form1::Form1_MouseMove(System::Object^  sender, System::Windows::Forms::MouseEventArgs^  e)
    {
      lblMouseXY->Text = String::Format("Mouse position: {0}", e->Location);
    }
    Note that, in fact, this event handler and the label essentially are the only two things that differ between the test project and a freshly created, i.e. empty, Windows Forms project created by the IDE. I have attached the test project to this post to play with, but it should really be no problem to create an equivalent one yourself.

    Also note that in the attached test project as well as the code snippet above I have separated the implementation of the event handler from its declaration in the class body in Form1.h and put it into a separate implementation file (Form1.cpp), as explained in http://www.codeguru.com/forum/showthread.php?p=2032109. This is a thing I generally recommend to do. However, the one-line function body of the event handler above of course would work the same when pasted into the empty implementation generated by the IDE in Form1.h.
    Attached Files Attached Files
    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.

  9. #9
    Join Date
    Sep 2011
    Posts
    10

    Re: C++ CLI Form Problems - Label Display

    It looks like maybe you made that Test4 file in VS2010? I only have 2008 so I can't open it, but its ok. I think I understand how to get things done now.

    Thanks again for your help! You really saved me a lot of aggravation.

  10. #10
    Join Date
    Jun 2010
    Location
    Germany
    Posts
    2,675

    Re: C++ CLI Form Problems - Label Display

    Quote Originally Posted by SpartanGuy07 View Post
    It looks like maybe you made that Test4 file in VS2010? I only have 2008 so I can't open it, but its ok. I think I understand how to get things done now.
    Yes, I made it in VC++ 2010. Even though you can't open the project, you can of course use the .cpp and .h files, since they're plain text files. But beware of simply copying any .h file associated to a form (like the Form1.h in this project) into an existing project. These files are used by the Forms Designer that would pretty much get messed up that way. You can, however, copy pieces of code from such a .h file into your project, as long as you don't touch the Forms Designer code enclosed by #pragma region and #pragma endregion.

    At any rate, the only essential thing is the tiny code snippet I already posted in post #8, so the concrete project isn't that important.

    Thanks again for your help! You really saved me a lot of aggravation.
    You're welcome!
    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.

Tags for this Thread

Posting Permissions

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





Click Here to Expand Forum to Full Width

Featured