Adding control to form from other class - c#

I'm trying to create picturebox in class and add it to form with method, it doesn't have any errors but it doesn't display picturebox
Class:
class Igrac
{
public int ID;
public string Ime;
public int Polje;
public int Novac;
public Igrac(int id, string ime, int polje, int novac)
{
ID = id;
Ime = ime;
Polje = polje;
Novac = novac;
}
public void Pijun (int LocX,Image image, Form1 form)
{
PictureBox pijun = new PictureBox();
pijun.Size = new Size(20, 40);
pijun.Location = new Point(LocX,655);
pijun.Image = image;
form.Controls.Add(pijun);
}
}
Main program:
private void Form1_Load(object sender, EventArgs e)
{
Igrac igrac1 = new Igrac(1, ImeIgraca1, 0, 10000);
igrac1.Pijun(643, Properties.Resources.Pijun1,this);
}

I have pasted your code and its works fine, but check parameters in new Point(LocX, 655) contructor. If it is larger than form size, control will be outer window, because (0,0) point is on left upper corner.

It was overlapped by another control...

Related

C# Forms add text to textbox from other class

I have a C# Form called Form1.cs and a Class in the same project called RandWord.cs.
Now I want to add text to the textbox (tbRandom) from the class.
I added the following code to Form1.cs:
public TextBox tbRandom;
And the following code to the class:
public RandWord()
{
//get linecount
int linesGerman = File.ReadAllLines(pathGerman).Length;
int linesFrance = File.ReadAllLines(pathFrance).Length;
//check if same linecount
if (linesGerman == linesFrance)
{
//new random int
Random rnd = new Random();
int rndLine = rnd.Next(1, File.ReadAllLines(pathGerman).Length);
//write to Form1's Textbox tbWord
f1.tbRandom.Text = rndLine.ToString();
MessageBox.Show(rndLine.ToString());
}
}
The messagebox is just there to prove that the Int is not empty. But the textbox won't display anything. There is no Exception aswell. The class is called by a button ( RandWord(); )
Any ideas?
In you From1 :
public TextBox tbRandom =new TextBox() ;
private void Form1_Load(object sender, EventArgs e)
{
this.Controls.Add(tbRandom);
}
public string TextBoxTxt {
get { return txtText1.Text; }
set { txtText1.Text = value; }
}
//Your button RandWord
private void RandWord_Click(object sender, EventArgs e)
{
RandWord(this);
}
Your class RandWord :
public RandWord(Form f1)
{
//get linecount
int linesGerman = File.ReadAllLines(pathGerman).Length;
int linesFrance = File.ReadAllLines(pathFrance).Length;
//check if same linecount
if (linesGerman == linesFrance)
{
//new random int
Random rnd = new Random();
int rndLine = rnd.Next(1, File.ReadAllLines(pathGerman).Length);
//write to Form1's Textbox tbWord
f1.TextBoxTxt = rndLine.ToString();
MessageBox.Show(rndLine.ToString());
}
}
You can write a contractor method for your class and pass the TextBox to it, and you can access the TextBox from there.
class GenerateRandomWord
{
TextBox _t;
public GenerateRandomWord(TextBox t)
{
_t = t;
}
public void RandWord()
{
_t.Text = "Something!";
}
}

C#: Form width used in class does not refresh when form resized

I am working on some school work and I am wondering if you could solve this.
I got my form.cs code and my class apple.cs(some snake fruit generation)
I choosed that my apple is being randomly spawned accros the form width/height, but when I resize that form, It keeps to spawn within old "borders" of the form.
Can I reload it somehow?
class Apple {
Random nc = new Random();
Form1 hl;
//Properties
public Color Color { get; set; }
public Size Size { get; set; }
public Point Pt { get; set; }
//constructors
public Apple()
{
hl = new Form1();
int s = 10;
this.Color = Color.Red;
this.Size = new Size(s,s);
this.Pt = new Point(nc.Next(s,hl.panel1.Width-(2*s-1)),nc.Next(s,hl.panel1.Height-(2*s-1)));
}
//methods
public void drawOutPoint(Graphics kp)
{
kp.FillRectangle(new SolidBrush(Color), new Rectangle(Bod, Size));
}
}
Thank you very much!
or you can try this
public Apple(double width,double height)
{
\\your code and assign the values
}
and in the form you define the object
apple ap=new applw(this.width,this.height);
let the apple get the width and high from the form using
double width= this.width;
and the same for high

c# List.Add() unable to add correct values

Program suppose to draw shapes on panel1.
This is code for my main form:
namespace DrawShapes
{
public partial class Form1 : Form
{
List<Shape> myShapeList;
Shape shape;
public Form1()
{
InitializeComponent();
}
public void AddShape(Shape myshape)
{
myShapeList.Add(shape);
}
public List<Shape> MyShapeList
{
get { return myShapeList; }
}
private void Form1_Load(object sender, EventArgs e)
{
myShapeList = new List<Shape>();
shape = new Shape();
}
private void drawMeButton_Click(object sender, EventArgs e)
{
EditShape editShape = new EditShape();
editShape.Shape = shape;
if (editShape.ShowDialog() == DialogResult.OK)
{
this.shape = editShape.Shape;
myShapeList.Add(shape);
panel1.Invalidate();
}
editShape.Dispose();
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
int panelWidth = panel1.ClientRectangle.Width;
int panelHeight = panel1.ClientRectangle.Height;
Pen penLine = new Pen(Color.Blue, 1);
Graphics g = e.Graphics;
if (myShapeList != null)
{
foreach (Shape element in myShapeList)
{
label1.Text = element.Width.ToString();
g.DrawRectangle(penLine, element.XCordinates, element.XCordinates, 50, 50);
}
}
}
}
}
and here is code for my edit shape dialog box
namespace DrawShapes
{
public partial class EditShape : Form
{
Shape shape = null;
public EditShape()
{
InitializeComponent();
}
public Shape Shape
{
get { return shape; }
set { shape = value; }
}
private void button1_Click(object sender, EventArgs e)
{
shape.Width = 50;
shape.Height = 50;
shape.XCordinates = int.Parse(textBox1.Text);
shape.YCordinates = int.Parse(textBox2.Text);
shape.Type = 0;
DialogResult = DialogResult.OK;
}
}
}
I am having problem assigning shape object(from Edit Shape form) to myShapeList, all properties are set to 0 for some reason. Please help.
Perhaps the problem is your AddShape method. You seem to be adding shape each time instead of the shape that's getting passed into the method (myshape).
What happens if you do this instead?
public void AddShape(Shape myshape)
{
myShapeList.Add(myshape); // myshapeinstead of shape
}
It seems that you're not actually adding your shape to your shapelist. You're taking in myShape and then trying to add in shape. This should come up as an intellisense error.
public void AddShape(Shape myshape)
{
myShapeList.Add(shape);
}
EDIT: Nevermind, it wouldn't come up as an error because you have a member variable named shape. You're getting zero for everything because it's calling the default constructor for shape.
The big problem is in your call to the edit form. You are adding to the list the same object reference. So when you modify the reference inside the edit form you change all the elements added to the list to the inputs set in the latest call
Change your code to
private void drawMeButton_Click(object sender, EventArgs e)
{
using(EditShape editShape = new EditShape())
{
// Here, create a new instance of a Shape and edit it....
editShape.Shape = new Shape();
if (editShape.ShowDialog() == DialogResult.OK)
{
// Add the new instance to the list, not the same instance
// declared globally. (and, at this point, useless)
myShapeList.Add(editShape.Shape);
panel1.Invalidate();
}
// The using blocks makes this call superflous
// editShape.Dispose();
}
}
Then it is not clear when you call the method AddShape(Shape myshape) but it is clear that you have typo in that method
I have found my mistake.I Created new event handler with wrong parameters. Therefore information that suppose to be passed by my dialog OK button was never correctly assigned. Silly mistake. Thanks guys.

Exploiting the OOP more effectively

I'm looking for a possibiltiy to shape my program in a better way and would like to exploit the object-oriented approach more effectively.
public ScrollingBackground(int width, int height, int speed, string title, Bitmap path)
{
intBreite = width;
intHoehe = height;
intFeinheitDerBewegungen = speed;
stringTitel = title;
bitmapBildpfad = path;
this.Text = title;
this.Size = new Size(this.intBreite, this.intHoehe);
this.StartPosition = FormStartPosition.CenterScreen;
this.FormBorderStyle = FormBorderStyle.FixedSingle;
this.MaximizeBox = false;
timerBewegungImage = new Timer();
timerBewegungImage.Tick += new EventHandler(bewegungImage_XRichtung_Tick);
timerBewegungImage.Interval = constIntInterval;
timerBewegungImage.Start();
////
picBoxImage = new PictureBox();
picBoxImage.Image = global::Flugzeugspiel.Properties.Resources.MyFlugzeug;
picBoxImage.BackColor = Color.Transparent;
picBoxImage.SetBounds(100, 100, 125, 50);
this.Controls.Add(picBoxImage);
////
listPicBoxAufeinanderfolgendeImages = new PictureBox[2];
imageInWinFormLadenBeginn();
this.ShowDialog();
}
As you can see the constructor above that the code enclosed by the slashes is located in the constructor ScrollingBackground.
It is important for me that this contructor should contain code only relating to the Scrolling Background but not the image MyFlugzeug.png.
This image (of course the whole code enclosed by the slashes) should be swapped into my main class Flugzeug.
using System;
using System.Drawing;
using System.Windows.Forms;
public abstract class Flugzeug : Form
{
private PictureBox picBoxImage;
protected int lebensanzeige = 10;
public virtual void nachObenUntenFliegen(string pathOfMovingObject, int xPositionObject, int yPositionObject, int widthOfObject, int heightOfObject)
{
// The code in the upper constructor enclosed by the slashes should stand here. Here I'd like to ensure the control of the airplane which has to be still programmed.
}
public int getLebensanzeige()
{
return lebensanzeige;
}
public int getTreffer(int schussstaerke)
{
return lebensanzeige = lebensanzeige - schussstaerke;
}
}
How is it possible to transfer the code from the constructor to the class Flugzeug?
I've tried something but it didn't work.
I've tried sth. like this:
public class MyFlugzeugspiel
{
public static void Main()
{
MyFlugzeug myPlane = new MyFlugzeug(10);
ScrollingBackground hintergrund = new ScrollingBackground(1000, 650, 5, "THE FLIGHTER", global::Flugzeugspiel.Properties.Resources.Himmel, myPlane);
...
public abstract class Flugzeug : Form
{
private PictureBox picBoxImage;
protected int lebensanzeige = 10;
public virtual void nachObenUntenFliegen(string pathOfMovingObject, int xPositionObject, int yPositionObject, int widthOfObject, int heightOfObject)
{
picBoxImage = new PictureBox();
picBoxImage.Image = global::Flugzeugspiel.Properties.Resources.MyFlugzeug;
picBoxImage.BackColor = Color.Transparent;
picBoxImage.SetBounds(100, 100, 125, 50);
this.Controls.Add(picBoxImage);
}
...
public ScrollingBackground(int width, int height, int speed, string title, Bitmap path, Flugzeug plane)
{
intBreite = width;
intHoehe = height;
intFeinheitDerBewegungen = speed;
stringTitel = title;
bitmapBildpfad = path;
this.plane = plane;
plane.nachObenUntenFliegen("Path", 0, 0, 100, 100);
this.Text = title;
this.Size = new Size(this.intBreite, this.intHoehe);
this.StartPosition = FormStartPosition.CenterScreen;
this.FormBorderStyle = FormBorderStyle.FixedSingle;
this.MaximizeBox = false;
...
But this isn't right, is it? Nothing happens. The airplane won't appear on the Scrolling Background.
Who can help me solving this problem?
You could make a Control or Form out of your ScrollingBackground class, and derive from it (or use it as control) in your Flugzeug form.
If you think deriving is the best option, your class signature should look like this:
public class ScrollingBackground : Form { }
public class Flugzeug : ScrollingBackground { }
If you like a control better, you should expose the required properties from the ScrollingBackground class, so you can access them in your Flugzeug class.

I have a context problem with c#

I have a problem with 2 Windows Forms which I created in c#. The first form (menu) has a PrintPreviewDialog object. The "menu" form then instantiates a copy of the send class "file" and call a ShopDialog method.
The "file" class write a file and calls a method (direct) in the "menu" class.
The problem I have is that the "direct" method is not known to the "menu" class. I think the answer is to define a copy of "menu" class in the "file", but I can't see have to do that.
Thanks for any help in advance.
John
namespace CSharp
{
public partial class MainMenu : Form
{
// Fields for printing.
public PrintDocument printDocument1 = new PrintDocument();
PageSettings printPageSettings = new PageSettings();
static RichTextBox printRichTextBox = new RichTextBox();
static string stringToPrint = "";
Font printFont = new Font("Arial", 10);
/****************************************************
* Select the Data->File-IO menu item. *
****************************************************/
private void fileIoToolStripMenuItem1_Click(object sender, EventArgs e)
{
File_IO fileIoDialog = new File_IO();
fileIoDialog.ShowDialog();
}
/****************************************************
* Initiate the printing process. The data to be *
* printed will be read from a file and stored in a*
* rich text box. The print menu buttons are *
* enabled. *
****************************************************/
public static void PrintInitialise(String printSource)
{
try
{
// Read text file and load into printRichTextBox.
FileStream printStream = new FileStream(printSource, FileMode.Open, FileAccess.Read);
printRichTextBox.LoadFile(printSource, RichTextBoxStreamType.PlainText);
printStream.Close();
// Initialise string to print.
stringToPrint = printRichTextBox.Text;
}
catch (Exception ex)
{
// Display error message if they appear.
MessageBox.Show(ex.Message);
}
}
/****************************************************
* Select the Data->File-IO menu item. *
****************************************************/
public void PrintDirect()
{
printDocument1.Print();
}
/****************************************************
* Select the Data->File-IO menu item. *
****************************************************/
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
int numChars;
int numLines;
string stringForPage;
StringFormat strFormat = new StringFormat();
// Based on page setup, define drawable rectangle on page
}
}
}
namespace `enter code here`CSharp
{
public partial class File_IO : Form
{
MainMenu mainBransom;
public File_IO()
{
InitializeComponent();
}
private void btnPrint_Click(object sender, EventArgs e)
{
MainMenu.PrintInitialise(printSource);
mainBransom.PrintDirect();
}
You could use a property to store a reference to the menu class in the send class.
public class send: Form
{
public send(Form menuForm)
{
menu = menuForm;
}
public Form menu { get; private set; }
//... some other methods and properties
public void SomeButton_Click(object sender, EventArgs e)
{
// you have access to the direct method (provided it is public)
menu.direct();
}
}
In order to instantiate the send class you need to pass a reference to the menu form.

Categories