How to refer to the sender object?
Oct 9, 2009 at 2:31pm UTC
Okay I'm trying to write one function to handle all button clicks in my TicTacToe game (it's just a practice project).
Right now I have 9 functions, one for each button. Here's the function for button1:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
private : System::Void button_DoClick1(System::Object^ sender, System::EventArgs^ e)
{
if (b1val == 0)
{
if (player == 1)
{
Button^ NewBut = *sender;
button1->BackgroundImage = System::Drawing::Image::FromFile("S:\\tictactoe\\release\\x.jpg" );
bval1 = 1;
player = 2;
label1->Text=L"Player 2 Turn" ;
}
else if (player == 2)
{
button1->BackgroundImage = System::Drawing::Image::FromFile("S:\\tictactoe\\release\\o.jpg" );
bval1 = 2;
player = 1;
label1->Text=L"Player 1 Turn" ;
}
b1val = 1;
turns++;
}
else
{
if (winner == 0)
MessageBox::Show("This space has already been used!" );
}
CheckWinner();
}
I have 9 of these. Picture how redundant that is lol. So how would I refer to the button that was clicked, rather than hard code "button1->BackgroundImage etc."
I tried this:
1 2 3 4 5
sender->BackgroundImage = System::Drawing::Image::FromFile("S:\\tictactoe\\release\\x.jpg" );
//and
this ->BackGroundImage = System::Drawing::Image::FromFile("S:\\tictactoe\\release\\x.jpg" );
The first one throws an error:
error C2039: 'BackgroundImage' : is not a member of 'System::Object'
The latter one simply changes the background of the entire button ><
Oct 9, 2009 at 2:54pm UTC
Did some digging on my own and found the solution:
Button^ ctrl = safe_cast<Button^>(sender);
#Solved
(:
Topic archived. No new replies allowed.