protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
var cp = new Point(Width / 2, Height / 2);
DrawGradientCircle(e.Graphics, cp, 100);
}
private void DrawGradientCircle(Graphics gr, Point cp, float radius)
{
var path = new GraphicsPath();
path.AddEllipse(cp.X - radius, cp.Y - radius, 2 * radius, 2 * radius);
using (var brush = new PathGradientBrush(path))
{
var blends = new ColorBlend(7);
blends.Colors[0] = Color.Violet;
blends.Positions[0] = 0;
blends.Colors[1] = Color.Blue;
blends.Positions[1] = 0.16f;
blends.Colors[2] = Color.Aqua;
blends.Positions[2] = 0.32f;
blends.Colors[3] = Color.Lime;
blends.Positions[3] = 0.48f;
blends.Colors[4] = Color.Yellow;
blends.Positions[4] = 0.64f;
blends.Colors[5] = Color.Orange;
blends.Positions[5] = 0.82f;
blends.Colors[6] = Color.Red;
blends.Positions[6] = 1;
brush.InterpolationColors = blends;
gr.FillPath(brush, path);
}
}
There is my code - i just want to draw the circle after button click, but how to do it?
But I don't know how make a link
If I understood you right, you could have a boolean variable and set it to true when you click the button... something like:
private bool _buttonClicked = false;
void myButton_Click(object sender, EventArgs e)
{
_buttonClicked = true;
this.Invalidate(); // <-- invalidate the form so it's repainted
this.Update(); // <-- optional: force a synchronous repaint
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
if(!_buttonClicked) return;
// this will only happen after button is clicked
var cp = new Point(Width / 2, Height / 2);
DrawGradientCircle(e.Graphics, cp, 100);
}
Don't forget to assign myButton_Click to the button's Click event
Related
I'm drawing a custom toolstrip using ToolStripProfessionalRender and editing the OnRenderItemText event as follows:
protected override void OnRenderItemText(ToolStripItemTextRenderEventArgs e)
{
e.Item.ForeColor = Clr.White;
e.Item.TextAlign = ContentAlignment.MiddleLeft;
e.Item.Alignment = ToolStripItemAlignment.Left;
base.OnRenderItemText(e);
if (e.Item.GetType() == typeof(ToolStripDropDownButton))
{
ToolStripDropDownButton tsmi = (ToolStripDropDownButton)e.Item;
if (tsmi.HasDropDownItems && tsmi.OwnerItem == null)
{
Rectangle bounds = tsmi.Bounds;
bounds.X = bounds.Right - 25;
bounds.Width = 25;
bounds.Y = 10;
// Draw the corner
Graphics G = e.Graphics;
SolidBrush brushw = new SolidBrush(Color.FromArgb(70,70,70));
Point[] points =
{
new Point(bounds.Right - 3, bounds.Height - 11), // point top right
new Point(bounds.Right - 3, bounds.Bottom - 14), // point bottom right
new Point(bounds.Right - 10, bounds.Bottom - 14) // point bottom left
};
G.FillPolygon(brushw, points);
}
}
}
and basically the output i'm trying to obtain is the following:
So drawing a little triangle on the bottom right corner when i got a ToolStripDropDownButton. The problem is that the little triangle is drawn only first item.
To end up the question i draw this toolstrip dynamically using a function that adds a dropdownbutton at each call.
ToolStripDropDownButton m_Item = new ToolStripDropDownButton(text, image);
m_Item.ImageAlign = ContentAlignment.MiddleCenter;
m_Item.ImageScaling = ToolStripItemImageScaling.None;
m_Item.Name = name;
m_Item.ForeColor = Color.White;
m_Item.BackColor = Color.FromArgb(95, 95, 95);
m_Item.Padding = new Padding(5);
m_Item.ShowDropDownArrow = false;
m_Item.Paint += new PaintEventHandler(this.PaintButtonBorder);
if (tabPage != null)
m_Item.Click += (sender, e) => AddClickTab(sender, e, tabPage);
((ToolStripDropDownMenu)m_Item.DropDown).ShowImageMargin = false;
((ToolStripDropDownMenu)m_Item.DropDown).ShowCheckMargin = false;
((ToolStripDropDownMenu)m_Item.DropDown).Cursor = Cursors.Hand;
toolStrip1.Items.Add(m_Item);
if (SubItems != null)
{
for(int i = 0; i < SubItems.Length; i++)
{
object[] subitem = (object[])SubItems[i];
FnAddToolStripMenuItem(
subitem[0].ToString(),
subitem[1].ToString(),
(Bitmap)subitem[2],
m_Item,
(TabPage)subitem[3]
);
}
}
Am i missing some "new" maybe?
Override the OnRenderItemText method only to draw the text part as it says, and/or to set the default properties used when rendering the text. To change the look and the shape of the arrows of the dropdown items, override the OnRenderArrow method.
Example
using System.Drawing;
using System.Drawing.Drawing2D;
protected override void OnRenderArrow(ToolStripArrowRenderEventArgs e)
{
// Optional: to be the default color of the arrows.
e.ArrowColor = Color.FromArgb(70, 70, 70);
if (e.Item is ToolStripDropDownButton item && item.OwnerItem == null)
{
var g = e.Graphics;
var r = new Rectangle(item.Bounds.Width - 10, item.Bounds.Height - 10, 8, 8);
g.SmoothingMode = SmoothingMode.AntiAlias;
g.PixelOffsetMode = PixelOffsetMode.Half;
using (var br = new SolidBrush(e.ArrowColor))
g.FillPolygon(br, new[]
{
new Point(r.Left, r.Bottom),
new Point(r.Right, r.Top),
new Point(r.Right, r.Bottom)
});
g.SmoothingMode = SmoothingMode.None;
g.PixelOffsetMode = PixelOffsetMode.Default;
}
else
base.OnRenderArrow(e);
}
protected override void OnRenderItemText(ToolStripItemTextRenderEventArgs e)
{
e.Item.ForeColor = Color.White;
e.Item.TextAlign = ContentAlignment.MiddleLeft;
e.Item.Alignment = ToolStripItemAlignment.Left;
base.OnRenderItemText(e);
}
Make sure to enable the ShowDropDownArrow property of the dropdown buttons. So comment this m_Item.ShowDropDownArrow = false;.
If you are also interested to change the color according to the current state of the dropdown button (Selected, Pressed), then you can do for example:
using (var br = new SolidBrush(item.Selected
? Color.FromArgb(150, 150, 150) : item.Pressed
? Color.FromArgb(100, 100, 100) :
Color.FromArgb(70, 70, 70)))
//...
Here is the following rectangle below:
When I resize the form, I need this rectangle to match the size of the form.
When changing the width of the rectangle, do not interfere with its visibility within the form.
I'm using the following:
Note:
I did the rectangle manually, but if you have rectangle ready, better yet!
public Form1()
{
InitializeComponent();
this.Paint += Form1_Paint;
this.rectangles = new Dictionary<string, Rectangle>();
this.sizeScreen = this.Size;
this.sizeRectangles = new Size(8, 8);
this.brush = new SolidBrush(Color.Red);
FillLeft();
FillRight();
FillUp();
FillDown();
}
private Size sizeScreen;
private Size sizeRectangles;
private SolidBrush brush;
private Dictionary<string, Rectangle> rectangles;
private void FillLeft()
{
Rectangle rectangle = new Rectangle()
{
Height = this.sizeScreen.Height,
Width = this.sizeRectangles.Width,
X = 0,
Y = this.sizeRectangles.Height
};
this.rectangles.Add("left", rectangle);
}
private void FillRight()
{
Rectangle rectangle = new Rectangle()
{
Height = this.sizeScreen.Height,
Width = this.sizeRectangles.Width,
X = this.sizeScreen.Width - (this.sizeRectangles.Width * 5),
Y = this.sizeRectangles.Height
};
this.rectangles.Add("right", rectangle);
}
private void FillUp()
{
Rectangle rectangle = new Rectangle()
{
Height = this.sizeRectangles.Height,
Width = this.sizeScreen.Width,
X = 0,
Y = this.sizeRectangles.Height
};
this.rectangles.Add("up", rectangle);
}
private void FillDown()
{
Rectangle rectangle = new Rectangle()
{
Height = this.sizeRectangles.Height,
Width = this.sizeScreen.Width,
X = 0,
Y = this.sizeScreen.Height - (this.sizeRectangles.Height * 11)
};
this.rectangles.Add("down", rectangle);
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
for (int i = 0; i < this.rectangles.Count; i++)
{
e.Graphics.FillRectangles(this.brush, this.rectangles.Values.ToArray());
}
}
I want to set the rectangle on the form when it is resized
This is the way I'm creating the rectangle, but it does not stay right on the screen, to resize it I do not know
I think this would simplify what you are trying to do:
const int PenWidth = 10;
private void Form1_Paint(object sender, PaintEventArgs e)
{
Rectangle r = this.ClientRectangle;
Pen pen = new Pen(Color.Red, PenWidth);
e.Graphics.DrawRectangle(pen, r);
}
You could even add a margin:
const int PenWidth = 10;
const int PenMargin = 10;
private void Form1_Paint(object sender, PaintEventArgs e)
{
Rectangle r = this.ClientRectangle;
r.Inflate(-PenMargin, -PenMargin);
Pen pen = new Pen(Color.Red, PenWidth);
e.Graphics.DrawRectangle(pen, r);
}
To prevent traces (suggested by Wyck):
private void Form1_Resize(object sender, EventArgs e)
{
Invalidate();
}
Handle the Resize event and call Invalidate in the handler. Create a Pen of the desired color and width and set its Alignment to Inset. Handle the Paint event and in the handler call DrawRectangle passing in the ClientRectangle of the form.
Here is an example.
const float borderWidth = 8.0f;
Pen borderPen = new Pen(Color.Red, borderWidth) { Alignment = System.Drawing.Drawing2D.PenAlignment.Inset };
public Form2()
{
InitializeComponent();
this.Paint += Form2_Paint;
this.Resize += Form2_Resize;
}
private void Form2_Resize(object sender, EventArgs e)
{
Invalidate();
}
private void Form2_Paint(object sender, PaintEventArgs e)
{
e.Graphics.DrawRectangle(borderPen, this.ClientRectangle);
}
Apply the following fixes to the code:
Set ResizeRedraw property of the form to true. It sets the underlying style for the form so by each resize it sends the paint message and you don't need to handle Resize event.
Use DrawRectangle and draw using wide pen. So you don't need to fill multiple rectangles.
Set the PenAlignment to Inset. So you don't need to calculate the location of rectangle.
Do dispose the pen when you don't need it.
Example
public Form1()
{
InitializeComponent();
ResizeRedraw = true;
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
using (var pen = new Pen(Color.Red, PenWidth))
{
pen.Alignment = System.Drawing.Drawing2D.PenAlignment.Inset;
e.Graphics.DrawRectangle(pen, ClientRectangle);
}
}
i have used this on my current project. when ever you resize the form, it will automatically resize all the object inside your form
i have class named clsResize and i call this on the form load.
1st you have to initialize the class inside the form then create 2 new method.
see example below
public partial class frmNewForm : Form
{
clsResize _form_resize;
public string selectedProd;
public frmNewForm()
{
InitializeComponent();
_form_resize = new clsResize(this);
this.Load += _Load;
this.Resize += _Resize;
}
private void _Load(object sender, EventArgs e)
{
_form_resize._get_initial_size();
}
private void _Resize(object sender, EventArgs e)
{
_form_resize._resize();
}
}
and here is the class that i used.
public class clsResize
{
List<System.Drawing.Rectangle> _arr_control_storage = new List<System.Drawing.Rectangle>();
private bool showRowHeader = false;
public clsResize(Form _form_)
{
form = _form_; //the calling form
_formSize = _form_.ClientSize; //Save initial form size
_fontsize = _form_.Font.Size; //Font size
}
private float _fontsize { get; set; }
private System.Drawing.SizeF _formSize {get;set; }
private Form form { get; set; }
public void _get_initial_size() //get initial size//
{
var _controls = _get_all_controls(form);//call the enumerator
foreach (Control control in _controls) //Loop through the controls
{
_arr_control_storage.Add(control.Bounds); //saves control bounds/dimension
//If you have datagridview
if (control.GetType() == typeof(DataGridView))
_dgv_Column_Adjust(((DataGridView)control), showRowHeader);
}
}
public void _resize() //Set the resize
{
double _form_ratio_width = (double)form.ClientSize.Width /(double)_formSize.Width; //ratio could be greater or less than 1
double _form_ratio_height = (double)form.ClientSize.Height / (double)_formSize.Height; // this one too
var _controls = _get_all_controls(form); //reenumerate the control collection
int _pos = -1;//do not change this value unless you know what you are doing
try
{
foreach (Control control in _controls)
{
// do some math calc
_pos += 1;//increment by 1;
System.Drawing.Size _controlSize = new System.Drawing.Size((int)(_arr_control_storage[_pos].Width * _form_ratio_width),
(int)(_arr_control_storage[_pos].Height * _form_ratio_height)); //use for sizing
System.Drawing.Point _controlposition = new System.Drawing.Point((int)
(_arr_control_storage[_pos].X * _form_ratio_width), (int)(_arr_control_storage[_pos].Y * _form_ratio_height));//use for location
//set bounds
control.Bounds = new System.Drawing.Rectangle(_controlposition, _controlSize); //Put together
//Assuming you have a datagridview inside a form()
//if you want to show the row header, replace the false statement of
//showRowHeader on top/public declaration to true;
if (control.GetType() == typeof(DataGridView))
_dgv_Column_Adjust(((DataGridView)control), showRowHeader);
//Font AutoSize
control.Font = new System.Drawing.Font(form.Font.FontFamily,
(float)(((Convert.ToDouble(_fontsize) * _form_ratio_width) / 2) +
((Convert.ToDouble(_fontsize) * _form_ratio_height) / 2)));
}
}
catch(Exception e)
{
MessageBox.Show(e.Message);
return;
}
}
private void _dgv_Column_Adjust(DataGridView dgv, bool _showRowHeader) //if you have Datagridview
//and want to resize the column base on its dimension.
{
int intRowHeader = 0;
const int Hscrollbarwidth = 5;
if (_showRowHeader)
intRowHeader = dgv.RowHeadersWidth;
else
dgv.RowHeadersVisible = false;
for (int i = 0; i < dgv.ColumnCount; i++)
{
if (dgv.Dock == DockStyle.Fill) //in case the datagridview is docked
dgv.Columns[i].Width = ((dgv.Width - intRowHeader) / dgv.ColumnCount);
else
dgv.Columns[i].Width = ((dgv.Width - intRowHeader - Hscrollbarwidth) / dgv.ColumnCount);
}
}
private static IEnumerable<Control> _get_all_controls(Control c)
{
return c.Controls.Cast<Control>().SelectMany(item =>
_get_all_controls(item)).Concat(c.Controls.Cast<Control>()).Where(control =>
control.Name != string.Empty);
}
}
I'm quite new at C#, but I'm trying to move a picturebox, by pressing the up-down-left-right keys from the keyboard, in a grid TableLayoutPanel(I made the grid at runtime). The grid is 23x23, has brickblock images border(each cell at the border contains a brickblock image in an imagebox) and an imagebox with a mouse in the middle. What I'm trying to do is moving the mouse image from the central cell(which is 11x11) in another cell by pressing one of the control keys mentioned above. It seems I can't get a grip on the idea of eventHandler... . The code works very good 'till I want to make the picturebox move. I've put the whole code, maybe the problem is in a place I didn't notice, but I think that the problem is KeyDown += new KeyEventHandler(Form2_KeyDown) or/end private void Form2_KeyDown(object sender, KeyEventArgs e){...} .
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;
namespace IndividualProject
{
public partial class Form2 : Form
{
PictureBox picturebox5 = new PictureBox
{
Visible = true,
Anchor = AnchorStyles.Top,
SizeMode = PictureBoxSizeMode.Normal,
Dock = DockStyle.Fill,
Margin = new Padding(0)
};
public Form2()
{
InitializeComponent();
// MaximizeBox = false;
//size
int h = Screen.PrimaryScreen.WorkingArea.Height / 2;
int w = Screen.PrimaryScreen.WorkingArea.Width / 2;
Size = new Size(w / 2 + w / 7, h + h / 4 + h / 7);
//location
StartPosition = FormStartPosition.CenterScreen;
//form style
FormBorderStyle = FormBorderStyle.FixedSingle;
//menuStrip1.BackColor = Color.Beige;
//lives and score container
#region livesAndScore
lasContainer.Size = new Size(Width / 2 + Width / 3 + Width / 7, Height / 13);
lasContainer.BackColor = Color.Lavender;
lasContainer.BorderStyle = BorderStyle.Fixed3D;
lasContainer.Dock = DockStyle.Top;
lasContainer.SplitterDistance = Width / 2 - Width / 69;
//labels
lives.Location = new Point(lasContainer.Panel1.Width / 12, lives.Height / 2);
score.Location = new Point(lasContainer.Panel2.Width / 12, score.Height / 2);
//picturebox
live3.Location = new Point(lasContainer.Panel1.Width / 3, lives.Height / 2);
live2.Location = new Point(lasContainer.Panel1.Width / 2, lives.Height / 2);
live1.Location = new Point(lasContainer.Panel1.Width / 2 + lasContainer.Panel1.Width / 6, lives.Height / 2);
#endregion livesAndScore
//gamePanel
gamePanel.Dock = DockStyle.Fill;
gamePanel.BackColor = Color.SkyBlue;
gamePanel.CellBorderStyle = TableLayoutPanelCellBorderStyle.Single; // REMOVE WHEN FINISHED !!!!!!!!!!!
//making the grid
#region grid
gamePanel.ColumnCount = 23;
gamePanel.RowCount = 23;
gamePanel.ColumnStyles.Clear();
gamePanel.RowStyles.Clear();
int iIndex, jIndex = 0;
for (iIndex = 0; iIndex < gamePanel.ColumnCount; iIndex++)
{
gamePanel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 4.34F));
gamePanel.RowStyles.Add(new RowStyle(SizeType.Percent, 4.34F));
}
#endregion grid
while(jIndex < gamePanel.ColumnCount)
{
#region picturebox1
PictureBox picturebox1 = new PictureBox
{
Visible = true,
Anchor = AnchorStyles.Top,
SizeMode = PictureBoxSizeMode.Normal,
BackColor = Color.Sienna,
Dock = DockStyle.Fill,
Margin = new Padding(0)
};
if(jIndex < gamePanel.ColumnCount - 1)
{
gamePanel.Controls.Add(picturebox1, jIndex, 0);
picturebox1.ImageLocation = #"..\..\ResourcesPh\brickblock.png";
}
#endregion picturebox1
#region picturebox2
PictureBox picturebox2 = new PictureBox
{
Visible = true,
Anchor = AnchorStyles.Top,
SizeMode = PictureBoxSizeMode.Normal,
BackColor = Color.Sienna,
Dock = DockStyle.Fill,
Margin = new Padding(0)
};
if (jIndex < gamePanel.ColumnCount - 1)
{
gamePanel.Controls.Add(picturebox2, 0, jIndex + 1);
picturebox2.ImageLocation = #"..\..\ResourcesPh\brickblock.png";
}
#endregion picturebox2
#region picturebox3
PictureBox picturebox3 = new PictureBox
{
Visible = true,
Anchor = AnchorStyles.Top,
SizeMode = PictureBoxSizeMode.Normal,
BackColor = Color.Sienna,
Dock = DockStyle.Fill,
Margin = new Padding(0)
};
if(jIndex < gamePanel.ColumnCount - 1)
{
gamePanel.Controls.Add(picturebox3, gamePanel.ColumnCount - 1 - jIndex, gamePanel.RowCount - 1);
picturebox3.ImageLocation = #"..\..\ResourcesPh\brickblock.png";
}
#endregion picturebox3
#region picturebox4
PictureBox picturebox4 = new PictureBox
{
Visible = true,
Anchor = AnchorStyles.Top,
SizeMode = PictureBoxSizeMode.Normal,
BackColor = Color.Sienna,
Dock = DockStyle.Fill,
Margin = new Padding(0),
};
if(jIndex < gamePanel.ColumnCount - 1)
{
gamePanel.Controls.Add(picturebox4, gamePanel.ColumnCount - 1, gamePanel.RowCount - 1 - jIndex - 1);
picturebox4.ImageLocation = #"..\..\ResourcesPh\brickblock.png";
}
#endregion picturebox4
jIndex++;
}
//the starting point of the mouse
#region mouseStartPoint
//PictureBox picturebox5 = new PictureBox
//{
// Visible = true,
// Anchor = AnchorStyles.Top,
// SizeMode = PictureBoxSizeMode.Normal,
// BackColor = Color.Sienna,
// Dock = DockStyle.Fill,
// Margin = new Padding(0)
//};
gamePanel.Controls.Add(picturebox5, 11, 11);
picturebox5.ImageLocation = #"..\..\ResourcesPh\mouse.png";
#endregion mouseStartPoint
KeyDown += new KeyEventHandler(Form2_KeyDown);
}
private void Form2_KeyDown(object sender, KeyEventArgs e)
{
int x = 11, y = 11;
if (e.KeyCode == Keys.Right)
x += 1;
if (e.KeyCode == Keys.Left)
x -= 1;
if (e.KeyCode == Keys.Up)
y -= 1;
if (e.KeyCode == Keys.Down)
y += 1;
gamePanel.Controls.Remove(picturebox5);
gamePanel.Controls.Add(picturebox5, x, y);
picturebox5.ImageLocation = #"..\..\ResourcesPh\mouse.png";
Refresh();
}
private void howToPlayToolStripMenuItem_Click(object sender, EventArgs e)
{
Hide();
Form3 f3 = new Form3();
f3.FormClosed += (s, args) => Close(); //event handler on closing Form2 after Form3 is opened
f3.Show();
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
TableLayoutPanel Grid
You are always setting the starting position back to 11, 11 on every key click. Move your declaration outside of that scope:
int x = 11, y = 11;
private void Form2_KeyDown(object sender, KeyEventArgs e) {
Here's a greatly simplified approach for moving your mouse, I get straight to the point and kept things to a bare minimum, yet effective :D
Here are the tiles I've used:
And here's the code !
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
private Dictionary<int, Image> _dictionary;
private Size _imageSize;
private int[] _level;
private Size _levelSize;
private Point _mousePos;
public Form1()
{
InitializeComponent();
pictureBox1.Paint += PictureBox1_Paint;
}
private void Form1_Load(object sender, EventArgs e)
{
InitializeLevel();
Redraw();
}
private void InitializeLevel()
{
var imageEmpty = Image.FromFile("empty.png");
var imageMouse = Image.FromFile("mouse.png");
var imageWall = Image.FromFile("wall.png");
_level = new[]
{
0, 0, 0, 0, 0,
0, 1, 1, 1, 0,
0, 1, 1, 1, 0,
0, 1, 1, 1, 0,
0, 0, 0, 0, 0
};
_levelSize = new Size(5, 5);
_imageSize = new Size(25, 25);
_dictionary = new Dictionary<int, Image>();
_dictionary.Add(0, imageWall);
_dictionary.Add(1, imageEmpty);
_dictionary.Add(2, imageMouse);
_mousePos = new Point();
}
private void Redraw()
{
pictureBox1.Invalidate();
}
private void PictureBox1_Paint(object sender, PaintEventArgs e)
{
var graphics = e.Graphics;
graphics.Clear(Color.Transparent);
// draw level
var i = 0;
foreach (var tile in _level)
{
var x = i % _levelSize.Width;
var y = i / _levelSize.Width;
var image = _dictionary[tile];
graphics.DrawImage(image, new Point(x * _imageSize.Width, y * _imageSize.Height));
i++;
}
// draw hero !
graphics.DrawImage(_dictionary[2], _mousePos);
}
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
var up = keyData == Keys.Up;
var down = keyData == Keys.Down;
var left = keyData == Keys.Left;
var right = keyData == Keys.Right;
var processed = up || down || left || right;
if (!processed) return base.ProcessCmdKey(ref msg, keyData);
// move the hero !
var x = 0;
var y = 0;
if (left) x--;
if (right) x++;
if (up) y--;
if (down) y++;
_mousePos.X += x;
_mousePos.Y += y;
Redraw();
return true;
}
}
}
Obviously you'll still want to check collisions, define your logic and such ...
Go on and give it a try !
Welcome to SO and good luck :D
I recently started "learning" C#. Currently i am doing a some sort of a game for school project. I want to draw a circle on a form. I added a time every new circle is drawn every 1000 ms on a random place in form. But when i start my form nothing really happens.
namespace Vezba_4
{
public partial class Form1 : Form
{
// attempt is when you try to "poke" the circle
bool attempt = false;
int xc, yc, Br = 0, Brkr = 0;
Random R = new Random();
public Form1()
{
InitializeComponent();
timer1.Start();
}
// Br is the number of circles that player has successfully "poked". And Brkr is a total number of circles that have appeared on the game screen. the
private void timer1_Tick(object sender, EventArgs e)
{
Refresh();
SolidBrush cetka = new SolidBrush(Color.Red);
Graphics g = CreateGraphics();
xc = R.Next(15, ClientRectangle.Width - 15);
yc = R.Next(15, ClientRectangle.Height - 15);
g.FillEllipse(cetka, xc - 15, yc - 15, 30, 30);
Brkr++;
Text = Br + "FROM" + Brkr;
attempt = false;
g.Dispose();
cetka.Dispose();
}
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
if (attempt == false)
{
if ((e.X - xc) * (e.X - xc) + (e.Y - yc) * (e.Y - yc) <= 225) Br++;
Text = Br + " FROM " + Brkr++;
}
attempt = true;
}
What is in the InitializeComponent method generated in the designer Form1.Designer.cs?
Is the event handler for the timer tick there?
//
// timer1
//
this.timer1.Interval = 1000;
this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
Edit:
For the mousedown would have to confirm that the handler is there in Form.Designer.cs as well:
this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.Form1_MouseDown);
Here's the properties of the timer I used, I dont have a timer.Start() anyway, it's all just your code with the Enabled property set to true, and the interval 1000. [I noticed when I copied nothing happened, but when I set Enabled to true it started to appear.
You should draw your circle in Form1_Paint. Because it will be drawn only when Paint event fired, and when fired, it looks for Form1_Paint.
public partial class Form1 : Form
{
bool attempt = false;
int xc, yc, Br = 0, Brkr = 0;
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
if (attempt == false)
{
if ((e.X - xc) * (e.X - xc) + (e.Y - yc) * (e.Y - yc) <= 225) Br++;
Text = Br + " FROM " + Brkr++;
}
attempt = true;
}
public void Paaint()
{
SolidBrush cetka = new SolidBrush(Color.Red);
Graphics g = CreateGraphics();
xc = R.Next(15, ClientRectangle.Width - 15);
yc = R.Next(15, ClientRectangle.Height - 15);
g.FillEllipse(cetka, xc - 15, yc - 15, 30, 30);
Brkr++;
label1.Text = Br + "FROM" + Brkr;
attempt = false;
g.Dispose();
cetka.Dispose();
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
Paaint();
}
private void timer1_Tick(object sender, EventArgs e)
{
Invalidate();
}
Random R = new Random();
public Form1()
{
InitializeComponent();
}
}
how to make a crosshair cursor with help lines like this on screenshots:
I know how to make crosshire cursor:
this.Cursor = System.Windows.Forms.Cursors.Cross;
can be also something like that:
like in CAD software.
This is the code I use. x and y are the dimensions. In my case I can have some text on the cursor and this is name. If you want dots or dashes then you need to do that with the pen.
private Cursor crossCursor(Pen pen, Brush brush, string name, int x, int y) {
var pic = new Bitmap(x, y);
Graphics gr = Graphics.FromImage(pic);
var pathX = new GraphicsPath();
var pathY = new GraphicsPath();
pathX.AddLine(0, y / 2, x, y / 2);
pathY.AddLine(x / 2, 0, x / 2, y);
gr.DrawPath(pen, pathX);
gr.DrawPath(pen, pathY);
gr.DrawString(name, Font, brush, x / 2 + 5, y - 35);
IntPtr ptr = pic.GetHicon();
var c = new Cursor(ptr);
return c;
}
Just create two label box as lab_X_Axis and lab_Y_Axis.
In chart mousemove function code as shown below..
private void chart1_MouseMove(object sender, MouseEventArgs e)
{
lab_X_Axis.Location = new Point((e.X), 21);
lab_Y_Axis.Location = new Point(76, e.Y);
}
private void Form1_Load(object sender, EventArgs e)
{
lab_X_Axis.AutoSize = false;
lab_Y_Axis.AutoSize = false;
lab_X_Axis.Text="";
lab_Y_Axis.Text="";
lab_X_Axes.Size = new Size(1, 300);
lab_Y_Axes.Size = new Size(300, 1);
}