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 WindowsFormsApplication1
{
public partial class Engine : Form
{
int x, y;
int w, h;
Boolean running = false;
public Engine()
{
InitializeComponent();
}
private void Engine_Load(object sender, EventArgs e)
{
}
private void Engine_Paint(object sender, PaintEventArgs e)
{
}
private void XTB_TextChanged(object sender, EventArgs e)
{
if (XTB.Text.Equals("10"))
{
x = 10;
}
if (XTB.Text.Equals("20"))
{
x = 20;
}
}
private void YTB_TextChanged(object sender, EventArgs e)
{
if (YTB.Text.Equals("10"))
{
y = 10;
}
}
private void WTB_TextChanged(object sender, EventArgs e)
{
if (WTB.Text.Equals("8"))
{
w = 8;
}
if (WTB.Text.Equals("16"))
{
w = 16;
}
if (WTB.Text.Equals("32"))
{
w = 32;
}
}
private void HTB_TextChanged(object sender, EventArgs e)
{
if (HTB.Text.Equals("8"))
{
h = 8;
}
if (HTB.Text.Equals("16"))
{
h = 16;
}
if (HTB.Text.Equals("32"))
{
h = 32;
}
}
private void drawShapeOnForm()
{
Graphics g = this.CreateGraphics();
g.DrawRectangle(new Pen(Brushes.Blue), x, y, w, h);
g.FillRectangle(Brushes.Blue, x, y, w, h);
}
//Button draws square
private void COIN_Click(object sender, EventArgs e)
{
drawShapeOnForm();
}
private void Engine_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.A)
{
x--;
}
}
private void button1_Click(object sender, EventArgs e)
{
running = true;
if (running)
{
PlayerCreator.Enabled = false;
EnemyCreator.Enabled = false;
}
}
private void timer1_Tick(object sender, EventArgs e)
{
Invalidate();
}
}
}
My shape only appears for a few secs when I press the button to make it, I'm not to sure how to fix this.
When I press the button it appears and then disappears, but if the function is put on the void Engine_Paint() it will work just fine. Please help me fix this problem.
You need to do your drawing in the Paint handler, using e.Graphics. Do not use CreateGraphics.
From your button click, you can just call this.Invalidate(); to trigger a repaint.
Related
i Need to open a second serialPort in my Visual C# program to read data from my arduino.
it already worked fine, but in the case you see below it does not work..
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.Ports;
using CommandsPD4I;
namespace CSharpExample
{
public partial class CSharpExample : Form
{
public ComMotorCommands motor1;
public CSharpExample()
{
InitializeComponent();
motor1 = new ComMotorCommands();
motor1.SetSteps(Convert.ToInt32(numericSchritte.Value));
}
SerialPort arduino;
delegate void InvokeLB(string Data);
InvokeLB lbRecievedDelegate;
int xPos = 0;
private void StartBtn_Click(object sender, EventArgs e)
{
// Set comm settings for motor 1
motor1.SelectedPort = ComPortBox1.Text;
motor1.Baudrate = Convert.ToInt32(BaudrateBox1.Text);
// Set motor address
motor1.MotorAddresse = Convert.ToInt32(Motor1ID.Value);
// Set relative positioning mode
motor1.SetPositionType(1);
// Start travel profile
if (motor1.ErrorFlag)
{
StatusLabel1.Text = "Status 1: " + motor1.ErrorMessageString;
}
else
{
StatusLabel1.Text = "Status 1: OK";
}
}
private void StopBtn_Click(object sender, EventArgs e)
{
// Stop travel profile
motor1.StopTravelProfile();
}
private void timer1_Tick(object sender, EventArgs e)
{
lblPosition.Text = Convert.ToString(motor1.GetPosition());
lblStatus.Text = motor1.ErrorMessageString;
// this.chart1.Series["Kraft"].Points.AddXY(xPos, Convert.ToDouble(lblKraft.Text));
// xPos++;**strong text**
}
private void btnHoch_Click(object sender, EventArgs e)
{
motor1.SetDirection(0);
motor1.SetPositionType(1);
motor1.StartTravelProfile();
}
private void btnRunter_Click(object sender, EventArgs e)
{
motor1.SetDirection(1);
motor1.SetPositionType(1);
motor1.StartTravelProfile();
}
private void numericSchritte_ValueChanged(object sender, EventArgs e)
{
motor1.SetSteps(Convert.ToInt32(numericSchritte.Value));
}
private void numericGeschwindigkeit_ValueChanged(object sender, EventArgs e)
{
motor1.SetMaxFrequency(Convert.ToInt32(numericGeschwindigkeit.Value));
}
private void btnDiagramm_Click(object sender, EventArgs e)
{
if (timer1.Enabled)
{
timer1.Stop();
}
else
{
timer1.Start();
}
}
private void btnResetDiagramm_Click(object sender, EventArgs e)
{
this.chart1.Series["Kraft"].Points.Clear();
xPos = 0;
}
private void arduino_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
string RecievedLine = " ";
while (RecievedLine != "")
{
RecievedLine = arduino.ReadLine();
lblKraft.Invoke(lbRecievedDelegate, new object[] { RecievedLine });
}
}
void Invokelabel1(string Data)
{
label1.Text = Data;
this.chart1.Series["Kraft"].Points.AddXY(xPos, Convert.ToDouble(lblKraft.Text));
xPos++;
}
private void btnArduino_Click(object sender, EventArgs e)
{
//Hier erstellen wir unseren Serialport und legen die Einstellungen fest
arduino = new SerialPort("COM7", 9600);
if (!arduino.IsOpen)
{
arduino.Open();
if (arduino.IsOpen)
{
lblArduino.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(200)))), ((int)(((byte)(0)))));
lblArduino.Text = "Verbunden mit " + arduino.PortName;
}
}
lbRecievedDelegate = new InvokeLB(Invokelabel1);
arduino.DataReceived += new SerialDataReceivedEventHandler(arduino_DataReceived); //DataRecieved Event abonnieren
}
}
}
When i leave out this:
motor1.SelectedPort = ComPortBox1.Text;
motor1.Baudrate = Convert.ToInt32(BaudrateBox1.Text);
then it works..
I hope you can help :)
I make a graphic drawing panel [my own paint program] and I want save my own drawing. This is my all code:
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 pezeshk
{
public partial class pen : Form
{
private SolidBrush myBrush;
private Graphics myGraphics;
private bool isDrawing = false;
public pen()
{
InitializeComponent();
}
private void pen_Load(object sender, EventArgs e)
{
myBrush = new SolidBrush(panel2.BackColor);
myGraphics = panel1.CreateGraphics();
}
private void panel2_MouseDoubleClick(object sender, MouseEventArgs e)
{
if (colorDialog1.ShowDialog() == DialogResult.OK)
{
panel2.BackColor = colorDialog1.Color;
myBrush.Color = panel2.BackColor;
}
}
private void panel1_MouseDown(object sender, MouseEventArgs e)
{
isDrawing = true;
}
private void panel1_MouseUp(object sender, MouseEventArgs e)
{
isDrawing = false;
}
private void panel1_MouseMove(object sender, MouseEventArgs e)
{
if (isDrawing == true)
{
myGraphics.FillEllipse(myBrush, e.X, e.Y, trackBar1.Value, trackBar1.Value);
}
}
}
for everyone that need this code
this code works [thx to #Taw]
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 pezeshk
{
public partial class pen : Form
{
private SolidBrush myBrush;
private Pen myPen;
private Graphics myGraphics;
private bool isDrawing = false;
public pen()
{
InitializeComponent();
myPen = new Pen(Color.ForestGreen);
myBrush = new SolidBrush(Color.DarkSlateBlue);
}
void panel1_paint(object sender, PaintEventArgs e)
{
if (rb_pen.Checked)
{
if (points.Count > 1) e.Graphics.DrawCurve(myPen, points.ToArray());
foreach (List<Point> lp in curves)
if (lp.Count > 1)
e.Graphics.DrawCurve(myPen, lp.ToArray());
}
}
private void pen_Load(object sender, EventArgs e)
{
myBrush = new SolidBrush(panel2.BackColor);
myGraphics = panel1.CreateGraphics();
}
private void panel2_MouseDoubleClick(object sender, MouseEventArgs e)
{
if (colorDialog1.ShowDialog() == DialogResult.OK)
{
panel2.BackColor = colorDialog1.Color;
myBrush.Color = panel2.BackColor;
}
}
Point mDown = Point.Empty;
private void panel1_MouseDown(object sender, MouseEventArgs e)
{
mDown = e.Location;
}
private void panel1_MouseUp(object sender, MouseEventArgs e)
{
if (rb_pen.Checked)
{
if (points.Count > 1) curves.Add(points.ToList()); // copy!!
points.Clear();
panel1.Invalidate();
}
panel1.Invalidate();
}
private void panel1_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Left)
{
if (rb_pen.Checked)
{
points.Add(e.Location);
}
panel1.Invalidate();
}
}
List<Rectangle> circles = new List<Rectangle>();
List<Point> points = new List<Point>();
List<List<Point>> curves = new List<List<Point>>();
private void button1_Click(object sender, EventArgs e)
{
string somefolder = "D:\\"; using (Bitmap bmp = new Bitmap(panel1.ClientSize.Width, panel1.ClientSize.Height))
{
panel1.DrawToBitmap(bmp, panel1.ClientRectangle); bmp.Save(somefolder + panel1.Name + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
}
}
private void button2_Click(object sender, EventArgs e)
{
curves.Clear(); points.Clear(); panel1.Invalidate();
}
}
class DrawPanel : Panel
{
public DrawPanel() { DoubleBuffered = true; }
}
}
to start of Im not good at programming and I am completely new to it. With that said, I am trying to make a game, where a pattern of labels show up (by the speciffic labels changing colors), and then the user has to click that speciffic pattern after it has been shown. I have already made the pattern show, and put into a list. The problem I now have is how I am going to check if the correct label was licked, acording to the random pattern that has been made. Sorry if my code seems clumsy, but here it is (sorry that there are no commemts yet also):
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Spil
{
public partial class Form1 : Form
{
Random rnd = new Random();
Label[] labelArray;
int turn = 1;
int lives = 3;
List<Label> orderList = new List<Label>();
public Form1()
{
InitializeComponent();
labelArray = new Label []{ label1, label2, label3, label4, label5, label6, label7, label8, label9 };
}
private void DisplayOrder()
{
for (int i = 0; i < labelArray.Length; i++)
{
labelArray[i].BackColor = Color.Blue;
}
for (int i = -2; i < turn; i++)
{
int chosenNumber = rnd.Next(0, 9);
labelArray[chosenNumber].BackColor = Color.Green;
Thread.Sleep(1000);
labelArray[chosenNumber].BackColor = Color.Blue;
orderList.Add(labelArray[chosenNumber]);
}
}
private void Click0(object sender, EventArgs e)
{
}
private void Click1(object sender, EventArgs e)
{
}
private void Click2(object sender, EventArgs e)
{
}
private void Click3(object sender, EventArgs e)
{
}
private void Click4(object sender, EventArgs e)
{
}
private void Click5(object sender, EventArgs e)
{
}
private void Click6(object sender, EventArgs e)
{
}
private void Click7(object sender, EventArgs e)
{
}
private void Click8(object sender, EventArgs e)
{
}
private void Click9(object sender, EventArgs e)
{
}
private void Form1_Shown(object sender, EventArgs e)
{
System.Timers.Timer t = new System.Timers.Timer(100);
t.Elapsed += t_Elapsed;
t.Start();
}
void t_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
((System.Timers.Timer)sender).Stop();
DisplayOrder();
}
}
}
You can have all your labels registered for the same click event and use the sender parameter to identify the clicked label.
for (int i = 0; i < labelArray.Length; i++)
{
labelArray[i].BackColor = Color.Blue;
labelArray[i].Click += label_Click;
}
void label_Click(object sender, EventArgs e)
{
string name = ((Label)sender).Name;
}
You need to generate the Click even for each individual label,you can find the events tab here with the properties tab (in case you didn't know).Simply lick your label in the designer and navigate to the label_click event and double click it.
When this form opens, it has a background image of the fullscreen and the user can mouse down and draw a rectangle which will be used later to crop the background image. The problem I am getting is that when the form paints, it's not drawing a rectangle so the user doesnt know the the area they are selecting
This is my code:
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 Quick_Screenshot
{
public partial class Crop : Form
{
private Rectangle croprect = Rectangle.Empty;
private bool mouseDown = false;
private bool selectedArea = false;
Point sp, ep;
Bitmap background;
public Rectangle CropArea
{
get { return croprect; }
}
public bool SelectedArea
{
get { return selectedArea; }
}
public Crop(Bitmap image)
{
InitializeComponent();
background = image;
picBox.MouseDown += new MouseEventHandler(Crop_MouseDown);
picBox.MouseUp += new MouseEventHandler(Crop_MouseUp);
picBox.MouseMove += new MouseEventHandler(Crop_MouseMove);
picBox.Paint += new PaintEventHandler(Crop_Paint);
}
private void Crop_Load(object sender, EventArgs e)
{
picBox.Image = (Image)background;
}
private void Crop_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Right)
this.Close();
else
{
mouseDown = true;
sp = ep = e.Location;
}
}
private void Crop_MouseUp(object sender, MouseEventArgs e)
{
ep = e.Location;
mouseDown = false;
croprect = GetRectangle(sp, ep);
if (croprect.Width > 10 && croprect.Height > 10)
{
selectedArea = true;
}
else
{
croprect = Rectangle.Empty;
Taskbar.Balloon("Selected area too small", "Quick Screenshot", ToolTipIcon.Error);
}
this.Close();
}
private void Crop_MouseMove(object sender, MouseEventArgs e)
{
if (mouseDown)
{
ep = e.Location;
Update();
}
}
private void Crop_Paint(object sender, PaintEventArgs e)
{
e.Graphics.DrawRectangle(Pens.Red, GetRectangle(sp, ep));
e.Graphics.Save();
}
private Rectangle GetRectangle(Point p1, Point p2)
{
return new Rectangle(
Math.Min(p1.X, p2.X),
Math.Min(p1.Y, p2.Y),
Math.Abs(p1.X - p2.X),
Math.Abs(p1.Y - p2.Y)
);
}
}
}
You should call the Invalidate() method on the picBox variable to refresh the control.
Instead of this:
private void Crop_MouseMove(object sender, MouseEventArgs e)
{
if (mouseDown)
{
ep = e.Location;
Update();
}
}
Use this:
private void Crop_MouseMove(object sender, MouseEventArgs e)
{
if (mouseDown)
{
ep = e.Location;
picBox.Invalidate();
}
}
You should call Invalidate() instead of Update()
I have a winform app and when i click on a button, i would like to have a string text move after my cursor. I've written some code but it doesn't seem to work . please Help !
Here is the code :
private void corectionBrushToolStripMenuItem_Click(object sender, EventArgs e)
{
this.MouseMove += new MouseEventHandler(On_MouseMove);
this.Paint += new PaintEventHandler(DrawRect);
}
private void DrawRect(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
g.DrawString("da",Font,Brushes.Black,new Point(mouseMoveX,mouseMoveY));
}
public void On_MouseMove(object sender, MouseEventArgs mouseEv)
{
mouseMoveX = mouseEv.X;
mouseMoveY = mouseEv.Y;
this.Invalidate();
}
Regards,
Alex Badescu
This is an example that does what you want I think. the offset in the mouse move is so that it shows up not under the mouse.
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 winap
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private bool DrawText = false;
private void button1_Click(object sender, EventArgs e)
{
DrawText = !DrawText;
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
if(DrawText)
{
if (lp != p)
{
this.Invalidate();
}
e.Graphics.DrawString("hi", SystemFonts.DefaultFont, Brushes.Green, p);
lp = p;
}
}
private PointF p;
private PointF lp;
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
p = new PointF(e.X -10, e.Y);
this.Invalidate();
}
}
}
How about:
Add the desired text to a label control, and change the position in MouseMove.
Following works fine:
int mX = 0;
int mY = 0;
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
mX = e.X;
mY = e.Y;
this.Invalidate();
}
Random rr = new Random(123123);
private void Form1_Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
g.DrawString("This a test"+rr.Next().ToString(), Font, Brushes.Black, new Point(mX, mY));
}