Programmatically add toolbar and their contents in c# - c#

I am a absolute beginner with a simple question(c# . i want to create a toolbar at runtime and their events . I am using visual studio 2008 , .net framework 3.5 , C# .

For example, in you form class you can make some like this:
ToolStrip toolStrip2 = new ToolStrip();
toolStrip2.Items.Add(new ToolStripDropDownButton());
toolStrip2.Dock = DockStyle.Bottom;
this.Controls.Add(toolStrip2);

using System;
using System.IO;
using System.Windows.Forms;
namespace DynamicToolStrip
{
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new DynamicToolStripForm());
}
class DynamicToolStripForm : Form
{
ToolStrip m_toolstrip = new ToolStrip();
public DynamicToolStripForm()
{
Controls.Add(m_toolstrip);
AddToolStripButtons();
}
void AddToolStripButtons()
{
const int iMAX_FILES = 5;
string[] astrFiles = Directory.GetFiles(#"C:\");
for (int i = 0; i < iMAX_FILES; i++)
{
string strFile = astrFiles[i];
ToolStripButton tsb = new ToolStripButton();
tsb.Text = Path.GetFileName(strFile);
tsb.Tag = strFile;
tsb.Click += new EventHandler(tsb_Click);
m_toolstrip.Items.Add(tsb);
}
}
void tsb_Click(object sender, EventArgs e)
{
ToolStripButton tsb = sender as ToolStripButton;
if (tsb != null && tsb.Tag != null)
MessageBox.Show(String.Format("Hello im the {0} button", tsb.Tag.ToString()));
}
}
}
}

Related

How to add dynamically created hyperlink to stack panel programmatically wpf

i am creating hyperlinks and want to add it to stack panel.
for (int i = 1; i <= links.Length; i++)
{
Hyperlink hyperlink = new Hyperlink()
{
NavigateUri = new Uri(links[i - 1])
};
}
hyperlink.RequestNavigate += new System.Windows.Navigation.RequestNavigateEventHandler(this.Hyperlink_RequestNavigate);
mainControl.Children.Add(hyperlink);
it gives me error -
cannot convert to system.windows.documents.hyperlink to system.windows.uielement.
i understand the namespace error but didn't find resolution because in uielement i dint find hyperlink.
Use LinkLabel instead of HyperLink
Samples:
using System;
using System.Drawing;
using System.Windows.Forms;
public class LinkLabelAddLink : Form {
LinkLabel lnkLA = new LinkLabel();
public LinkLabelAddLink(){
Size = new Size(300,250);
lnkLA.Parent = this;
lnkLA.Text = "StackOverflow.com";
lnkLA.Location = new Point(0,25);
lnkLA.AutoSize = true;
lnkLA.BorderStyle = BorderStyle.None;
lnkLA.Links.Add(0,7,"www.stackoverflow.com");
lnkLA.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(lnkLA_LinkClicked);
}
static void Main()
{
Application.Run(new LinkLabelAddLink());
}
private void lnkLA_LinkClicked(object sender,LinkLabelLinkClickedEventArgs e)
{
lnkLA.LinkVisited = true;
System.Diagnostics.Process.Start(e.Link.LinkData.ToString());
}
}
PS: You need atleast .NET 4.5

How can i pass and update in real time from a new form the pictureBox1 in form1?

I added a new form to my project the new form contain in the designer webBrowser control. What i'm doing is parsing from html some links then navigate to each link then taking a screenshot and save to the hard disk each image i navigated to in the webBrowser.
In the end when all the links navigated and i have the images on the hard disk i display them on Form1 pictureBox with a hScrollBar.
But now instead waiting for it to finish in the new form and then to show all the images i want to show each saved image on the hard disk in the pictureBox in form1.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.IO;
namespace WebBrowserScreenshots.cs
{
public partial class WebBrowserScreenshots : Form
{
private class MyComparer : IComparer<string>
{
[DllImport("shlwapi.dll", CharSet = CharSet.Unicode)]
private static extern int StrCmpLogicalW(string x, string y);
public int Compare(string x, string y)
{
return StrCmpLogicalW(x, y);
}
}
List<string> newHtmls = new List<string>();
string uri = "";
public bool htmlloaded = false;
int countlinks = 0;
public int numberoflinks = 0;
public int numberofimages = 0;
public List<string> imageList = new List<string>();
public WebBrowserScreenshots()
{
InitializeComponent();
webBrowser1.ScrollBarsEnabled = false;
webBrowser1.ScriptErrorsSuppressed = true;
NavigateToSites();
}
string test;
List<string> htmls;
private void GetLinks()
{
htmlloaded = true;
for (int i = 1; i < 304; i++)
{
if (newHtmls.Count == 1)
break;
backgroundWorker1.ReportProgress(i);
HtmlAgilityPack.HtmlWeb hw = new HtmlAgilityPack.HtmlWeb();
HtmlAgilityPack.HtmlDocument doc = hw.Load("http://test/page" + i);
htmls = new List<string>();
foreach (HtmlAgilityPack.HtmlNode link in doc.DocumentNode.SelectNodes("//a[#href]"))
{
string hrefValue = link.GetAttributeValue("href", string.Empty);
if (hrefValue.Contains("http") && hrefValue.Contains("attachment"))
htmls.Add(hrefValue);
}
if (htmls.Count > 0 && abovezero == false)
RealTimeHtmlList();
}
}
bool abovezero = false;
private void RealTimeHtmlList()
{
abovezero = true;
for (int x = 0; x < htmls.Count; x++)
{
test = htmls[x];
int index = test.IndexOf("amp");
string test1 = test.Substring(39, index - 25);
test = test.Remove(39, index - 35);
int index1 = test.IndexOf("amp");
if (index1 > 0)
test = test.Remove(index1, 4);
if (!newHtmls.Contains(test))
{
while (true)
{
if (htmlloaded == true)
{
newHtmls.Add(test);
RealTimeNavigate(test);
}
else
{
break;
}
}
}
}
}
private void RealTimeNavigate(string tests)
{
uri = test;
webBrowser1.Navigate(test);
htmlloaded = false;
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
GetLinks();
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
numberoflinks = e.ProgressPercentage;
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
numberofimages = newHtmls.Count;
htmlloaded = true;
}
private void NavigateToLinks()
{
if (countlinks != newHtmls.Count)
{
while (true)
{
if (htmlloaded == true)
{
uri = newHtmls[countlinks];
webBrowser1.Navigate(newHtmls[countlinks]);
countlinks++;
htmlloaded = false;
}
else
{
break;
}
}
}
}
int imagescount = 0;
public FileInfo[] filesinfo;
public bool savedall = false;
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if (e.Url.ToString() == uri)
{
Bitmap bmp = new Bitmap(SaveImageFromWebBrowser(webBrowser1));
bmp = ImageTrim.ImagesTrim(bmp);
bmp.Save(#"e:\webbrowserimages\Image" + imagescount.ToString() + ".bmp",
System.Drawing.Imaging.ImageFormat.Bmp);
bmp.Dispose();
imagescount++;
htmlloaded = true;
RealTimeHtmlList();
}
}
private void NavigateToSites()
{
backgroundWorker1.RunWorkerAsync();
}
[DllImport("user32.dll")]
public static extern bool PrintWindow(IntPtr hwnd, IntPtr hdcBlt, uint nFlags);
private Bitmap SaveImageFromWebBrowser(Control ctl)
{
Bitmap bmp = new Bitmap(ctl.ClientRectangle.Width, ctl.ClientRectangle.Height);
using (Graphics graphics = Graphics.FromImage(bmp))
{
IntPtr hDC = graphics.GetHdc();
try { PrintWindow(ctl.Handle, hDC, (uint)0); }
finally { graphics.ReleaseHdc(hDC); }
}
return bmp;
}
}
}
And in form1 i did:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Runtime.InteropServices;
namespace WebBrowserScreenshots.cs
{
public partial class Form1 : Form
{
private class MyComparer : IComparer<string>
{
[DllImport("shlwapi.dll", CharSet = CharSet.Unicode)]
private static extern int StrCmpLogicalW(string x, string y);
public int Compare(string x, string y)
{
return StrCmpLogicalW(x, y);
}
}
public List<string> imageList = new List<string>();
List<string> numbers = new List<string>();
WebBrowserScreenshots wbss;
public Form1()
{
InitializeComponent();
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
this.imageList = Directory.GetFiles(#"e:\webbrowserimages\", "*.bmp").ToList();
this.imageList.Sort(new MyComparer());
if (this.imageList.Count > 0)
{
hScrollBar1.Minimum = 0;
hScrollBar1.Value = 0;
hScrollBar1.Maximum = this.imageList.Count - 1;
hScrollBar1.SmallChange = 1;
hScrollBar1.LargeChange = 1;
pictureBox1.Image = Image.FromFile(this.imageList[0]);
}
else
{
timer1.Start();
wbss = new WebBrowserScreenshots();
wbss.Show();
}
}
FileInfo[] myFile;
private void timer1_Tick(object sender, EventArgs e)
{
if (wbss.savedall == true)
{
timer1.Stop();
hScrollBar1.Enabled = true;
hScrollBar1.Minimum = 0;
hScrollBar1.Value = 0;
hScrollBar1.Maximum = wbss.imageList.Count - 1;
hScrollBar1.SmallChange = 1;
hScrollBar1.LargeChange = 1;
pictureBox1.Image = Image.FromFile(wbss.imageList[0]);
}
else
{
if (wbss.htmlloaded == true)
{
var directory = new DirectoryInfo(#"e:\webbrowserimages\");
myFile = directory.GetFiles("*.bmp");
if (myFile.Length > 0)
{
var myFiles = (from f in directory.GetFiles("*.bmp")
orderby f.LastWriteTime descending
select f).First();
hScrollBar1.Enabled = true;
hScrollBar1.Minimum = 0;
hScrollBar1.Value = 0;
hScrollBar1.Maximum = 1;
hScrollBar1.SmallChange = 1;
hScrollBar1.LargeChange = 1;
pictureBox1.Image = Image.FromFile(myFiles.Name);
}
}
}
}
private void hScrollBar1_Scroll(object sender, ScrollEventArgs e)
{
int index = (int)hScrollBar1.Value;
if (pictureBox1.Image != null) pictureBox1.Image.Dispose();
if (this.imageList.Count > 0)
{
pictureBox1.Image = Image.FromFile(this.imageList[index]);
label1.Text = "Displaying image " + index + " of " + (this.imageList.Count - 1);
}
else
{
pictureBox1.Image = Image.FromFile(wbss.imageList[index]);
label1.Text = "Displaying image " + index + " of " + (wbss.imageList.Count - 1);
}
}
}
}
In form1 i have two options situations could be done.
Once if i'm using in the new form the way that i'm waiting for the backgroundworker to complete and then to wait untill it will navigate to all links in the List newHtmls and then after all images saved on hard disk for example 2453 images then i browse them in form1 pictureBox and hScrollBar.
Or the second option i'm using now that once an image saved to the hard disk in the new form then i will show the image in the form1 pictureBox1.
Then another image saved so now there are two images on hard disk so now show the last saved image. And so on once image saved display it on form1 pictureBox.
Just to show it. So i will see every X seconds images changing in form1 pictureBox.
The problem i'm facing now is in Form1 in this part:
if (wbss.htmlloaded == true)
{
var directory = new DirectoryInfo(#"e:\webbrowserimages\");
myFile = directory.GetFiles("*.bmp");
if (myFile.Length > 0)
{
var myFiles = (from f in directory.GetFiles("*.bmp")
orderby f.LastWriteTime descending
select f).First();
hScrollBar1.Enabled = true;
hScrollBar1.Minimum = 0;
hScrollBar1.Value = 0;
hScrollBar1.Maximum = 1;
hScrollBar1.SmallChange = 1;
hScrollBar1.LargeChange = 1;
pictureBox1.Image = Image.FromFile(myFiles.Name);
}
}
On the line:
pictureBox1.Image = Image.FromFile(myFiles.Name);
FileNotFoundException: Image3.bmp
But on my hard disk i see Image3.bmp
I will try to narrow cut some code but it's all connected the new form with form1.
You need to use myFiles.FullName. myFiles.Name only has the path relative to the directory the file is in, which is not enough to find the file. FullName includes the directory, so it's the full absolute path to the file.
And for gasake, name your controls. Form1 isn't a good name. pictureBox1 isn't a good name. Even the variable names are misleading - myFile for a collection of files, and then myFiles for a single file? And why are you calling GetFiles again when you already have a list in myFile? And why even check for file length? Why not just do directory.GetFiles("*.bmp").OrderByDescending(i => i.LastWriteTime).Select(i => i.FullName).FirstOrDefault()?

Coloring text using reflection

I'm trying to make a simple text editor that colors text in real time. I also must use DLL and Reflection for this.
I want to color the text while user typing. For that reason I have a checkbox. If it checked the text will be colored while user is typing (Real Time).
I've wrote a DLL file to do that.
Anyway, I'm very new to reflection thing.
The question:
I would want to ask you guys for your professional advice whether what I've wrote can be called "using reflection" or not? and if it's not, can point me what is wrong?
Here is my code (I've removed many things from it so the code will reflect the question but there might be leftovers)
using System;
using System.Drawing;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;
using System.Reflection;
namespace Editor
{
public class MainForm : Form
{
//Declaration of Controls
private RichTextBox EditRichTextBox;
private CheckBox chkBox;
private int flag = 0;
private Button[] PlugButton;
public string[] PluginNames;
private int NumofPlugins;
public MainForm()
{
//Initialization of Controls
this.EditRichTextBox = new RichTextBox();
this.ErrorTextBox = new RichTextBox();
this.chkBox = new CheckBox();
//Form
this.ClientSize = new Size(700, 500);
this.Name = "MainForm";
this.Text = "C# Editor";
//EditRichTextBox
this.EditRichTextBox.Location = new Point(20, 20);
this.EditRichTextBox.Name = "EditRichTextBox";
this.EditRichTextBox.Size = new Size(this.Width - 150, 300);
this.EditRichTextBox.AcceptsTab = true;
this.EditRichTextBox.Multiline = true;
//Controls on the Form
this.Controls.Add(this.ButtonCompilelib);
this.Controls.Add(this.ButtonCompile);
this.Controls.Add(this.ButtonRun);
this.Controls.Add(this.EditRichTextBox);
this.Controls.Add(this.ErrorTextBox);
this.Controls.Add(this.chkBox);
//CheckBox
this.chkBox.Location = new Point(600,300);
this.chkBox.Name = "chkBox";
this.chkBox.Text = "Color";
};
//My checkbox handler
this.chkBox.Click += (sender,e) =>
{
if(flag == 0)
{
flag = 1;
MessageBox.Show("Coloring Text");
}
else
flag = 0;
};
//My TextBox handler
this.EditRichTextBox.KeyPress += (sender,e) =>
{
try
{
string tmp = Environment.CurrentDirectory + "\\" + "mydll" + ".dll"; Assembly a = Assembly.LoadFrom(tmp);
Type t = a.GetType("MyPlugIn.colorclass");
MethodInfo mi = t.GetMethod("color");
Object obj = Activator.CreateInstance(t);
Object[] Params = new Object[5];
Params[0] = EditRichTextBox.Text;
Params[1] = EditRichTextBox.Handle;
Params[2] = ErrorTextBox.Handle;
Params[3] = EditRichTextBox;
Params[4] = flag;
mi.Invoke(obj, Params);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
};
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.Run(new MainForm());
}
}
}
And this is the DLL file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
namespace MyPlugIn
{
public class colorclass
{
public void color(string Text, Object Hndl_Text, Object Hndl_Err, RichTextBox box,int flag)
{
if (flag == 1)
{
int start = box.TextLength;
int end = box.TextLength;
//Textbox may transform chars, so (end-start) != text.Length
box.Select(start, end - start);
{
box.SelectionColor = Color.Blue;
}
box.SelectionLength = 0; // clear
}
}
}
}
Yes, your code uses Reflection. These lines are an example:
Type t = a.GetType("MyPlugIn.colorclass");
MethodInfo mi = t.GetMethod("color");
Object obj = Activator.CreateInstance(t);
Whether is the best approach or not, or whether it's necessary for this task, it's a different topic.

Why aren't the buttons in my C# Application working?

I am doing this lab out of a book on my own, and I made an application in which sharks are racing. There is a radio button that should update a label on the right dynamically, as well as a button that actually starts the race. Everything used to work and then I renamed a few things, and now nothing works.
Screenshot of application:
image http://cl.ly/f08f4e22761464e0c2f3/content
Form Class:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace project1
{
public partial class Game : Form
{
private Shark[] sharks;
private Guy[] guys;
private Guy selectedGuy;
public Game()
{
InitializeComponent();
Random moreRandom = new Random();
int start = myTrack.Location.X;
int finish = myTrack.Width - 65;
sharks = new Shark[4]
{
new Shark() {myRandom = moreRandom, myPictureBox = myShark1, myPBStart = start, trackLength = finish},
new Shark() {myRandom = moreRandom, myPictureBox = myShark2, myPBStart = start, trackLength = finish},
new Shark() {myRandom = moreRandom, myPictureBox = myShark3, myPBStart = start, trackLength = finish},
new Shark() {myRandom = moreRandom, myPictureBox = myShark4, myPBStart = start, trackLength = finish}
};
guys = new Guy[3]
{
new Guy() {myName="Joe", cash=50, myRadioButton=rbGuy1, myLabel=labelBet1},
new Guy() {myName="Bob", cash=75, myRadioButton=rbGuy2, myLabel=labelBet2},
new Guy() {myName="Al", cash=45, myRadioButton=rbGuy3, myLabel=labelBet3}
};
selectedGuy = guys[0];
rbGuy1.Tag = guys[0];
rbGuy2.Tag = guys[1];
rbGuy3.Tag = guys[2];
updateGui();
}
private void myChanged(object sender, EventArgs e)
{
selectedGuy = getSelectedGuy(sender);
betterLabel.Text = selectedGuy.myName;
}
private void betAmountValue(object sender, EventArgs e)
{
updateMin();
}
private void Bet_Click(object sender, EventArgs e)
{
int bet = (int) betAmount.Value;
int myFish = (int) sharkNumber.Value;
selectedGuy.placeBet(bet, myFish);
updateGui();
}
private void raceBtn_Click(object sender, EventArgs e)
{
betBtn.Enabled = false;
bool noWinner = true;
while(noWinner)
{
for (int dogFish = 0; dogFish < sharks.Length; dogFish++)
{
Application.DoEvents();
if(sharks[dogFish].Swim())
{
showWinner(dogFish);
collectBets(dogFish);
noWinner = false;
}
}
}
updateGui();
betBtn.Enabled = true;
}
private void showWinner(int fish)
{
MessageBox.Show(string.Format("Winner Winner People Dinner! \nShark {0} won!", fish + 1));
}
private void collectBets(int fish)
{
for (int guyNumber = 0; guyNumber < guys.Length; guyNumber++)
{
guys[guyNumber].collect(fish + 1);
guys[guyNumber].resetBet();
}
}
private void updateMin()
{
minBetLabel.Text = string.Format("Minimum bet: 5 bucks", betAmount.Value);
}
private Guy getSelectedGuy(object sender)
{
RadioButton rb = (RadioButton)sender;
return (Guy)rb.Tag;
}
private void updateGui()
{
for (int guyNumber = 0; guyNumber < guys.Length; guyNumber++)
{
guys[guyNumber].updateLabels();
}
for (int fish = 0; fish < sharks.Length; fish++)
{
sharks[fish].startPosition();
}
updateMin();
}
}
}
Shark Class:
using System;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;
namespace project1
{
public class Shark
{
public int myPBStart; // Where the PictureBox starts
public int trackLength; // How long the racetrack is
public PictureBox myPictureBox = null; // The PictureBox object
public int location = 0; // My location on the racetrack
public Random myRandom; // An instance of Random
public Shark()
{
location = 0;
myPictureBox = new PictureBox();
myRandom = new Random();
trackLength = 100;
myPBStart = 0;
}
public bool Swim()
{
int distance = myRandom.Next(1, 4);
location += distance;
movePB(distance);
return location > trackLength;
}
private void movePB(int distance)
{
Point p = myPictureBox.Location;
p.X += distance;
myPictureBox.Location = p;
}
public void startPosition()
{
location = myPBStart;
Point p = myPictureBox.Location;
p.X = location;
myPictureBox.Location = p;
}
}
}
I can supply more resources if needed, but this is the main gist of it.
Using Visual Studio, make sure of the following:
1) For each radio button, verify the CheckedChanged event is hooked up to your myChanged function.
2) Verify the "Bets" Button.Click event is hooked up to your Bet_Click function.
3) Verify the "Race!" Button.Click event is hooked up to your raceBtn_Click function.
A safe way to rename things is to right click on the variable name, Refactor, Rename. This will ensure any references to the variable are renamed properly
when you renamed them you probably did it by editing the code rather than by changing the control properties.
THe Winforms designer in VS created code for you behind the scenes that wires the invents up. This codes uses the control names. Look for a file called formname_designer.cs. Notice that there are lines that still have the old control names. You can change this code
This is why its a good habit to give controls nice names when you start.
Make sure that the events on your controls are still connected to the correct event handlers in your code. Sometimes when you rename things, this link can get broken.

The type or namespace name 'Button' could not be found (are you missing a using directive or an assembly reference?)

What am I missing I cant figure it out by the way this is a simple tic tac toe game.
Also how can I incorporate a listbox with a horizontal scrollbar to select the player?
Player1 = (x) Or Player2 = (O)
Thanks in advance!!!
Main Form - xGameForm
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace MyGame
{
public partial class xGameForm : Form
{
public Button xGameButton9;
public Button xGameButton8;
public Button xGameButton7;
public Button xGameButton6;
public Button xGameButton5;
public Button xGameButton4;
public Button xGameButton3;
public Button xGameButton2;
public Button xGameButton1;
public Button[] _buttonArray;
public bool isX;
public bool isGameOver;
Button tempButton = (Button)sender;
public xGameForm()
{
InitializeComponent();
}
public void xGameForm_Load(object sender, EventArgs e)
{
_buttonArray = new Button[9] { xGameButton1, xGameButton2, xGameButton3, xGameButton4, xGameButton5, xGameButton6, xGameButton7, xGameButton8, xGameButton9 };
for (int i = 0; i < 9; i++)
this._buttonArray[i].Click += new System.EventHandler(this.ClickHandler);
InitTicTacToe();
}
public void InitTicTacToe()
{
for (int i = 0; i < 9; i++)
{
_buttonArray[i].Text = "";
_buttonArray[i].ForeColor = Color.Black;
_buttonArray[i].BackColor = Color.LightGray;
_buttonArray[i].Font = new System.Drawing.Font("Microsoft Sans Serif", 24F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
}
this.isX = true;
this.isGameOver = false;
}
public void ClickHandler(object sender, System.EventArgs e)
{
Button tempButton = (Button)sender;
if( this.isGameOver )
{
MessageBox.Show("press reset to start a new game!","Game End",MessageBoxButtons.OK);
return;
}
if( tempButton.Text != "" )
{
return;
}
if( isX)
tempButton.Text = "X";
else
tempButton.Text = "O";
isX = !isX;
this.isGameOver = Result1.CheckWinner(_buttonArray );
}
public void xGameResetButton_Click(object sender, EventArgs e)
{
InitTicTacToe();
}
}
}
Class Result1
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MyGame
{
public class Result1
{
static private int[,] Winners = new int[,]
{
{0,1,2},
{3,4,5},
{6,7,8},
{0,3,6},
{1,4,7},
{2,5,8},
{0,4,8},
{2,4,6}
};
static public bool CheckWinner(Button[] myControls)
{
bool gameOver = false;
for (int i = 0; i < 8; i++)
{
int a = Winners[i, 0], b = Winners[i, 1], c = Winners[i, 2];
Button b1 = myControls[a], b2 = myControls[b], b3 = myControls[c];
if (b1.Text == "" || b2.Text == "" || b3.Text == "")
continue;
if (b1.Text == b2.Text && b2.Text == b3.Text)
{
b1.BackColor = b2.BackColor = b3.BackColor = Color.LightCoral;
b1.Font = b2.Font = b3.Font = new System.Drawing.Font("Microsoft Sans Serif", 32F, System.Drawing.FontStyle.Italic & System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
gameOver = true;
MessageBox.Show(b1.Text + " .... Wins the game!", "Game End", MessageBoxButtons.OK);
break;
}
}
return gameOver;
}
}
}
Button is a class in the System.Windows.Forms namespace.
Unless you import the namespace, the compiler won't know which class you want.
You need to import the namespace by adding using System.Windows.Forms; to the top of the class..
You need to add a using directive for using System.Windows.Forms into the file with you result1 class in it or explicitly reference System.Windows.Forms.Button. Otherwise the complire does not know what a button is.

Categories