Posted by: Zeeshan Amjad | September 11, 2009

Event handling in WPF using VC++


UIElement class introduced the routing event handling and introduced lots of core events. Here is a simple program to show the usages of Event handling of UIElement class.

  1: #include <windows.h>
  2: using namespace System;
  3: using namespace System::Windows;
  4: using namespace System::Windows::Media;
  5: using namespace System::Windows::Input;
  6: 
  7: public ref class MyUIElement : public UIElement
  8: {
  9: public:
 10: 	MyUIElement()
 11: 	{
 12: 		MouseLeftButtonDown += 
 13: 			gcnew MouseButtonEventHandler(this, &MyUIElement::OnMouseLeftButtonDown);
 14: 	}
 15: 
 16: 	virtual void OnRender(DrawingContext^ dc) override
 17: 	{
 18: 		Rect rect(Point(10, 10), Size(360, 250));
 19: 		LinearGradientBrush^ gBrush = gcnew LinearGradientBrush(Colors::AliceBlue, 
 20: 			Colors::Blue, Point(0,0), Point(1, 1));
 21: 		dc->DrawRoundedRectangle(gBrush, gcnew Pen(Brushes::Brown, 5),
 22: 			rect, 10, 10);
 23: 	}
 24: 
 25: 	void OnMouseLeftButtonDown(Object^ sender, MouseButtonEventArgs^ e)
 26: 	{
 27: 		String^ str = String::Format("Clicked at ({0}, {1})",
 28: 			e->GetPosition(this).X, e->GetPosition(this).Y);
 29: 		MessageBox::Show(str, "MyUIElement", MessageBoxButton::OK, MessageBoxImage::Information);
 30: 	}	
 31: };
 32: 
 33: public ref class MyWindow : public Window
 34: {
 35: public:
 36: 	MyWindow()
 37: 	{
 38: 		Title = "MyUIElement Class";
 39: 		Width = 400;
 40: 		Height = 300;
 41: 		WindowStartupLocation = Windows::WindowStartupLocation::CenterScreen;
 42: 		
 43: 		Content = gcnew MyUIElement();
 44: 	}
 45: };
 46: 
 47: [STAThread]
 48: int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
 49: 				   LPSTR lpCmd, int nCmd)
 50: {
 51: 	MyWindow^ win = gcnew MyWindow();
 52: 
 53: 	Application^ app = gcnew Application();
 54: 	app->Run(win);
 55: }
 56: 

The output of this program is one rounded rectangle. When user click on the window then it will display a message box with the point where user clicks on the window. Here is an output of this program. Here is the output of this program.

vcwpf_21

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: