C# drag mouse down - c#

I'm trying to make a program where when I click left click it drags the mouse down without me moving my mouse down for a game but it does not move the game at all. It moves my cursor outside of the game but does not move inside the game.
public static Point Position { get; set; }
public Anti_Recoil()
{
InitializeComponent();
}
private void Anti_Recoil_Load(object sender, EventArgs e)
{
this.BackColor = Color.Wheat;
this.TransparencyKey = Color.Wheat;
this.TopMost = true;
int initialStyle = GetWindowLong(this.Handle, -20);
SetWindowLong(this.Handle, -20, initialStyle | 0x80000 | 0x20);
PointConverter pc = new PointConverter();
Point pt = new Point();
pt = (Point)pc.ConvertFromString("765, 500");
Cursor.Position = pt;
}
private void Anti_Recoil_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Z)
Hide();
}

Use my class
First, add my class to your project
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Windows.Input;
namespace Hector.Framework.Utils
{
public class Peripherals
{
public class Mouse
{
public static int X
{
get => Cursor.Position.X;
}
public static int Y
{
get => Cursor.Position.Y;
}
public static void MoveToPoint(int X, int Y)
{
Win32.SetCursorPos(X, Y);
}
public static void Hide()
{
Cursor.Hide();
}
public static void Show()
{
Cursor.Show();
}
public static bool IsHidden
{
get => Cursor.Current == null;
}
/// <summary>
/// ButtonNumber: 0-None 1-Left 2-Middle 3-Right 4-XButton1 5-XButton2
/// </summary>
public static bool MouseButtonIsDown(int ButtonNumber)
{
bool outValue = false;
bool isLeft = Control.MouseButtons == MouseButtons.Left;
bool isRight = Control.MouseButtons == MouseButtons.Right;
bool isMiddle = Control.MouseButtons == MouseButtons.Middle;
bool isXButton1 = Control.MouseButtons == MouseButtons.XButton1;
bool isXButton2 = Control.MouseButtons == MouseButtons.XButton2;
switch (ButtonNumber)
{
case 0:
outValue = false;
break;
case 1:
outValue = isLeft;
break;
case 2:
outValue = isMiddle;
break;
case 3:
outValue = isRight;
break;
case 4:
outValue = isXButton1;
break;
case 5:
outValue = isXButton2;
break;
}
return outValue;
}
/// <summary>
/// This function is in Alpha Phase
/// </summary>
/// <param name="FocusedControl">The control that is scrolled; If the control has no focus, it will be applied automatically</param>
/// <param name="FontSize">This is used to calculate the number of pixels to move, its default value is 20</param>
static int delta = 0;
static int numberOfTextLinesToMove = 0;
static int numberOfPixelsToMove = 0;
public static bool GetWheelValues(Control FocusedControl, out int Delta, out int NumberOfTextLinesToMove, out int NumberOfPixelsToMove, int FontSize = 20)
{
try
{
if (FocusedControl == null) throw new NullReferenceException("The FocusedControl can not bel null");
if (!FocusedControl.Focused) FocusedControl.Focus();
FocusedControl.MouseWheel += (object sender, MouseEventArgs e) =>
{
delta = e.Delta;
numberOfTextLinesToMove = e.Delta * SystemInformation.MouseWheelScrollLines / 120;
numberOfPixelsToMove = numberOfTextLinesToMove * FontSize;
};
Delta = delta;
NumberOfTextLinesToMove = numberOfTextLinesToMove;
NumberOfPixelsToMove = numberOfPixelsToMove;
return true;
}
catch
{
Delta = 0;
NumberOfTextLinesToMove = 0;
NumberOfPixelsToMove = numberOfPixelsToMove;
return false;
}
}
private class Win32
{
[DllImport("User32.Dll")]
public static extern long SetCursorPos(int x, int y);
[DllImport("User32.Dll")]
public static extern bool ClientToScreen(IntPtr hWnd, ref POINT point);
[StructLayout(LayoutKind.Sequential)]
public struct POINT
{
public int x;
public int y;
}
}
}
}
}
Then where you need to check the mouse's status,
bool MouseLeftButton = Hector.Framework.Utils.Peripherals.Mouse.MouseButtonIsDown(1);
And try this:
private void Form2_Load(object sender, EventArgs e)
{
Hector.Framework.Utils.Peripherals.Mouse.MoveToPoint(300, 0); //Move the cursor to Top
}
//Then use timer to move the cursor
int a = 0;
private void timer1_Tick(object sender, EventArgs e)
{
Hector.Framework.Utils.Peripherals.Mouse.MoveToPoint(300, a += 1);
}
if(MouseLeftButton)
{
timer1.Start(); //timer is initialized
}

Related

Dragging a borderless form to a negative location

When dragging a borderless form to the top of the screen; if the Y coordinate is negative, it sets it back to 0. What I'm looking to do is be able to drag the form above the top, where the Y coordinate would be negative, the same way you can with every other side of the screen.
Here is what I have tried:
public partial class BorderlessForm : Form
{
public BorderlessForm()
{
InitializeComponent();
}
private bool _isNegative;
private Point _negative;
public const int WM_NCLBUTTONDOWN = 0xA1;
public const int HT_CAPTION = 0x2;
[DllImport("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
[DllImport("user32.dll")]
public static extern bool ReleaseCapture();
protected override void OnMouseDown(MouseEventArgs e)
{
if (e.Button == MouseButtons.Left) {
ReleaseCapture();
SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
}
}
protected override void OnResizeEnd(EventArgs e)
{
if (_isNegative) {
Location = _negative;
}
//base.OnResizeEnd(e);
}
protected override void OnMove(EventArgs e)
{
if (Location.Y < 0) {
_isNegative = true;
_negative = Location;
}
else {
_isNegative = false;
}
//base.OnMove(e);
}
}
This was the best I could come up with after thinking on it for a while. The problem is that when the mouse is released and the form is finished moving, OnMove is called before OnResizeEnd, and _isNegative is then set back to false. At least, that is what I assume is happening.
Do I have the right idea, or is there some better way to go about this?
So, I thought more about what isaeid said, and was able to come up with a solution. Still not sure if this is the best way to go about it, but here it is:
public partial class ImageForm : PerPixelAlphaForm
{
public ImageForm()
{
InitializeComponent();
}
private bool _isNegative;
private Point _negative;
private bool _flag;
protected override void OnMouseDown(MouseEventArgs e)
{
if (e.Button == MouseButtons.Left) {
NativeMethods.ReleaseCapture();
NativeMethods.SendMessage(Handle, NativeMethods.WM_NCLBUTTONDOWN, NativeMethods.HT_CAPTION, 0);
}
}
protected override void OnResizeEnd(EventArgs e)
{
if (_isNegative) {
Location = _negative;
_isNegative = false;
}
}
protected override void OnMove(EventArgs e)
{
if (Location.Y < 0) {
_isNegative = true;
_flag = true;
_negative = Location;
}
else {
if (_flag) {
_flag = false;
return;
}
_isNegative = false;
}
}
}
You can change some events like this:
protected override void OnResizeEnd(EventArgs e)
{
if (_isNegative)
{
Location = _negative;
}
oldRight = this.Right;
oldBottom = this.Bottom;
//base.OnResizeEnd(e);
}
protected override void OnMove(EventArgs e)
{
if ( this.Right == oldRight || this.Bottom == oldBottom)
return;
if (Location.Y < 0)
{
_isNegative = true;
_negative = Location;
}
else
{
_isNegative = false;
}
//base.OnMove(e);
}
When top or left of window is changed, dotnet determines location of window is changed and calls onmove event, i consider if right or bottom of the window is not changed so window's location is not changed.
Add this codes too:
int oldBottom, oldRight;
private void BorderlessForm_Load(object sender, EventArgs e)
{
oldRight = this.Right;
oldBottom = this.Bottom;
}

Unable to get objects to collide

For the life of me, I cannot figure out what I am doing wrong. I have managed to make a player and make it shoot. I've also managed to make balls spawn in at random locations/speeds in the picture box.
I can't get any Collision to work. I am trying to keep all balls in the picture box and bounce back and also bounce off each other, and then destroy them when shot.
I have been trying to use Ball.Bounds.IntersectsWith(pictureBox2.Bounds), but it seems that Ball.bounds is wrong.
I have a vague idea why it is wrong but not definitive. My property bounds in box.cs is either wrong or I don't know how to make that relate to positioning all my balls.
A little nudge in the right direction would be appreciated as I have been stuck on this issue for a while now.
ball.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace shootyarcher
{
class Ball : Box
{
public string bounds { get; set; }
static private Random generator = new Random();
private int countdown;
public Ball ()
{
pic = Properties.Resources.Balloon;
x = generator.Next(60, 1920);
y = generator.Next(100, 1000);
xspeed = generator.Next(-10, 4);
yspeed = generator.Next(-10, 4);
countdown = generator.Next(100, 200);
}
public new void Move()
{
countdown--;
if (countdown == 0)
{
xspeed = generator.Next(-4, 4);
yspeed = generator.Next(-4, 4);
countdown = generator.Next(20, 40);
}
x = x + xspeed;
y = y + yspeed;
}
}
}
box.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing; //pictures
namespace shootyarcher
{
class Box
{
public float x;
public float y;
public float w;
public float h;
public float xspeed;
public float yspeed;
public Image pic;
public Box() // constructor
{
x = 0;
y = 0;
xspeed = 0;
yspeed = 0;
}
public void Move()
{
x = x + xspeed;
y = y + yspeed;
}
public void Draw(Graphics g)
{
g.DrawImage (pic, x, y);
}
public float Width()
{
return pic.Width;
}
public float Height()
{
return pic.Height;
}
public float Left()
{
return x;
}
public float Right()
{
return x + Width();
}
public float Top()
{
return y;
}
public float Bottom()
{
return y + Height();
}
}
}
Form1.cs
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
namespace shootyarcher
{
public partial class Form1 : Form
{
Archer player;
List<Arrow> Shiv;
List<Ball> Kill;
public Form1()
{
InitializeComponent();
Cursor.Hide();
this.FormBorderStyle = FormBorderStyle.None;
this.TopMost = true;
this.Bounds = Screen.PrimaryScreen.Bounds;
player = new Archer(0, 0);
Shiv = new List<Arrow>();
Kill = new List<Ball>();
for (int i = 0; i < 400; i++)
{
Ball temp = new Ball();
Kill.Add(temp);
}
}
private void timer1_Tick(object sender, EventArgs e)
{
player.Move();
foreach (Arrow t in Shiv)
{
t.Move();
}
foreach (Ball m in Kill)
{
m.Move();
}
pictureBox1.Invalidate();
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.W)
{
player.moveup = true;
}
if (e.KeyCode == Keys.S)
{
player.movedown = true;
}
if (e.KeyCode == Keys.Space)
{
Arrow temp = new Arrow(player.x, player.y);
Shiv.Add(temp);
}
if (e.KeyCode == Keys.Escape)
{
this.Close();
}
}
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.W)
{
player.moveup = false;
}
if (e.KeyCode == Keys.S)
{
player.movedown = false;
}
}
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
player.Draw(e.Graphics);
foreach (Arrow t in Shiv)
{
t.Draw(e.Graphics);
}
foreach (Ball m in Kill)
{
m.Draw(e.Graphics);
}
}
}
}

Change Splitter Highlighting/Resize Line

I noticed when I resize an element in Visual Studio the Splitter Line is painted in a solid transparent black like this:
However in my own Winforms application I get this resize line:
I am wondering how I can change the painting of this resize line?
If you take a look at Splitter source code, you will see drawing of the highlight is performed in the DrawSplitHelper private method.
Since splitter methods are tightly deppending on private members of the control, overriding members or handling events of the control which use this method doesn't provides such transparent highlight simply. Also if you decide to darw a solid highlight, you can not have a filcker-free drawing because of the halftone highlight which the control draws in private methods.
The idea of showing a transparent highlight is based on showing a top-most semi-transparent window which doesn't activate on showing. Also you can use PatBlt method to draw a reversible rectangle using a brush.
As an option I started by Splitter.cs and changed it to draw desired transparent highlight as you see in image below:
Code
As an option I started by Splitter.cs and changed it to draw desired transparent highlight. I used a Form to show transparent highlight. I showed the form without activating, as top-most and with a suitable opacity.
Probably you can create a splitter using less code, but I preferred to use source code of Splitter instead of writing my own splitter. Thanks to Microsoft for sharing source code.
using System;
using System.ComponentModel;
using System.Drawing;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using System.Windows.Forms;
using System.Windows.Forms.Design;
using System.Drawing.Drawing2D;
using System.Reflection;
[ComVisible(true)]
[DefaultEvent("SplitterMoved")]
[DefaultProperty("Dock")]
[Designer(typeof(MySplitterDesigner))]
public class MySplitter : Control
{
private Point anchor = Point.Empty;
private System.Windows.Forms.BorderStyle borderStyle;
private const int defaultWidth = 3;
private const int DRAW_END = 3;
private const int DRAW_MOVE = 2;
private const int DRAW_START = 1;
private static readonly object EVENT_MOVED = new object();
private static readonly object EVENT_MOVING = new object();
private int initTargetSize;
private int lastDrawSplit = -1;
private int maxSize;
private int minExtra = 25;
private int minSize = 25;
private int splitSize = -1;
private Control splitTarget;
private SplitterMessageFilter splitterMessageFilter;
private int splitterThickness = 3;
[Category("Behavior")]
[Description("Occurs when the splitter is done being moved.")]
public event SplitterEventHandler SplitterMoved
{
add
{
base.Events.AddHandler(EVENT_MOVED, value);
}
remove
{
base.Events.RemoveHandler(EVENT_MOVED, value);
}
}
[Category("Behavior")]
[Description("Occurs when the splitter is being moved.")]
public event SplitterEventHandler SplitterMoving
{
add
{
base.Events.AddHandler(EVENT_MOVING, value);
}
remove
{
base.Events.RemoveHandler(EVENT_MOVING, value);
}
}
HighLight highlight;
public MySplitter()
{
base.SetStyle(ControlStyles.Selectable, false);
this.TabStop = false;
this.minSize = 0x19;
this.minExtra = 0x19;
this.Dock = DockStyle.Left;
highlight = new HighLight();
}
private void ApplySplitPosition()
{
this.SplitPosition = this.splitSize;
}
private SplitData CalcSplitBounds()
{
SplitData data = new SplitData();
Control control = this.FindTarget();
data.target = control;
if (control != null)
{
switch (control.Dock)
{
case DockStyle.Top:
case DockStyle.Bottom:
this.initTargetSize = control.Bounds.Height;
break;
case DockStyle.Left:
case DockStyle.Right:
this.initTargetSize = control.Bounds.Width;
break;
}
Control parentInternal = this.Parent;
Control.ControlCollection controls = parentInternal.Controls;
int count = controls.Count;
int num2 = 0;
int num3 = 0;
for (int i = 0; i < count; i++)
{
Control control3 = controls[i];
if (control3 != control)
{
switch (control3.Dock)
{
case DockStyle.Top:
case DockStyle.Bottom:
num3 += control3.Height;
break;
case DockStyle.Left:
case DockStyle.Right:
num2 += control3.Width;
break;
}
}
}
Size clientSize = parentInternal.ClientSize;
if (this.Horizontal)
{
this.maxSize = (clientSize.Width - num2) - this.minExtra;
}
else
{
this.maxSize = (clientSize.Height - num3) - this.minExtra;
}
data.dockWidth = num2;
data.dockHeight = num3;
}
return data;
}
private Rectangle CalcSplitLine(int splitSize, int minWeight)
{
Rectangle bounds = base.Bounds;
Rectangle rectangle2 = this.splitTarget.Bounds;
switch (this.Dock)
{
case DockStyle.Top:
if (bounds.Height < minWeight)
{
bounds.Height = minWeight;
}
bounds.Y = rectangle2.Y + splitSize;
return bounds;
case DockStyle.Bottom:
if (bounds.Height < minWeight)
{
bounds.Height = minWeight;
}
bounds.Y = ((rectangle2.Y + rectangle2.Height) - splitSize) - bounds.Height;
return bounds;
case DockStyle.Left:
if (bounds.Width < minWeight)
{
bounds.Width = minWeight;
}
bounds.X = rectangle2.X + splitSize;
return bounds;
case DockStyle.Right:
if (bounds.Width < minWeight)
{
bounds.Width = minWeight;
}
bounds.X = ((rectangle2.X + rectangle2.Width) - splitSize) - bounds.Width;
return bounds;
}
return bounds;
}
private int CalcSplitSize()
{
Control control = this.FindTarget();
if (control != null)
{
Rectangle bounds = control.Bounds;
switch (this.Dock)
{
case DockStyle.Top:
case DockStyle.Bottom:
return bounds.Height;
case DockStyle.Left:
case DockStyle.Right:
return bounds.Width;
}
}
return -1;
}
private void DrawSplitBar(int mode)
{
if ((mode != 1) && (this.lastDrawSplit != -1))
{
this.DrawSplitHelper(this.lastDrawSplit);
this.lastDrawSplit = -1;
}
else if ((mode != 1) && (this.lastDrawSplit == -1))
{
return;
}
if (mode != 3)
{
this.DrawSplitHelper(this.splitSize);
this.lastDrawSplit = this.splitSize;
}
else
{
if (this.lastDrawSplit != -1)
{
this.DrawSplitHelper(this.lastDrawSplit);
}
this.lastDrawSplit = -1;
highlight.Hide();
}
Console.WriteLine(mode);
}
private void DrawSplitHelper(int splitSize)
{
if (this.splitTarget != null)
{
Rectangle rectangle = this.CalcSplitLine(splitSize, 3);
var r = this.Parent.RectangleToScreen(rectangle);
if (!highlight.Visible)
highlight.ShowInactiveTopmost();
highlight.Location = r.Location;
highlight.Size = r.Size;
}
}
private Control FindTarget()
{
Control parentInternal = this.Parent;
if (parentInternal != null)
{
Control.ControlCollection controls = parentInternal.Controls;
int count = controls.Count;
DockStyle dock = this.Dock;
for (int i = 0; i < count; i++)
{
Control control2 = controls[i];
if (control2 != this)
{
switch (dock)
{
case DockStyle.Top:
if (control2.Bottom != base.Top)
{
break;
}
return control2;
case DockStyle.Bottom:
if (control2.Top != base.Bottom)
{
break;
}
return control2;
case DockStyle.Left:
if (control2.Right != base.Left)
{
break;
}
return control2;
case DockStyle.Right:
if (control2.Left != base.Right)
{
break;
}
return control2;
}
}
}
}
return null;
}
private int GetSplitSize(int x, int y)
{
int num;
if (this.Horizontal)
num = x - this.anchor.X;
else
num = y - this.anchor.Y;
int num2 = 0;
switch (this.Dock)
{
case DockStyle.Top:
num2 = this.splitTarget.Height + num;
break;
case DockStyle.Bottom:
num2 = this.splitTarget.Height - num;
break;
case DockStyle.Left:
num2 = this.splitTarget.Width + num;
break;
case DockStyle.Right:
num2 = this.splitTarget.Width - num;
break;
}
return Math.Max(Math.Min(num2, this.maxSize), this.minSize);
}
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if ((this.splitTarget != null) && (e.KeyCode == Keys.Escape))
this.SplitEnd(false);
}
protected override void OnMouseDown(MouseEventArgs e)
{
base.OnMouseDown(e);
if ((e.Button == MouseButtons.Left) && (e.Clicks == 1))
this.SplitBegin(e.X, e.Y);
}
protected override void OnMouseMove(MouseEventArgs e)
{
base.OnMouseMove(e);
if (this.splitTarget != null)
{
int x = e.X + base.Left;
int y = e.Y + base.Top;
Rectangle rectangle = this.CalcSplitLine(this.GetSplitSize(e.X, e.Y), 0);
int splitX = rectangle.X;
int splitY = rectangle.Y;
this.OnSplitterMoving(new SplitterEventArgs(x, y, splitX, splitY));
}
}
protected override void OnMouseUp(MouseEventArgs e)
{
base.OnMouseUp(e);
if (this.splitTarget != null)
{
Rectangle rectangle = this.CalcSplitLine(this.GetSplitSize(e.X, e.Y), 0);
this.SplitEnd(true);
}
}
protected virtual void OnSplitterMoved(SplitterEventArgs sevent)
{
SplitterEventHandler handler = (SplitterEventHandler)base.Events[EVENT_MOVED];
if (handler != null)
handler(this, sevent);
if (this.splitTarget != null)
this.SplitMove(sevent.SplitX, sevent.SplitY);
}
protected virtual void OnSplitterMoving(SplitterEventArgs sevent)
{
SplitterEventHandler handler = (SplitterEventHandler)base.Events[EVENT_MOVING];
if (handler != null)
handler(this, sevent);
if (this.splitTarget != null)
this.SplitMove(sevent.SplitX, sevent.SplitY);
}
protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified)
{
if (this.Horizontal)
{
if (width < 1)
width = 3;
this.splitterThickness = width;
}
else
{
if (height < 1)
height = 3;
this.splitterThickness = height;
}
base.SetBoundsCore(x, y, width, height, specified);
}
private void SplitBegin(int x, int y)
{
SplitData data = this.CalcSplitBounds();
if ((data.target != null) && (this.minSize < this.maxSize))
{
this.anchor = new Point(x, y);
this.splitTarget = data.target;
this.splitSize = this.GetSplitSize(x, y);
try
{
if (this.splitterMessageFilter != null)
this.splitterMessageFilter = new SplitterMessageFilter(this);
Application.AddMessageFilter(this.splitterMessageFilter);
}
finally { }
this.Capture = true;
this.DrawSplitBar(1);
}
}
private void SplitEnd(bool accept)
{
this.DrawSplitBar(3);
this.splitTarget = null;
this.Capture = false;
if (this.splitterMessageFilter != null)
{
Application.RemoveMessageFilter(this.splitterMessageFilter);
this.splitterMessageFilter = null;
}
if (accept)
this.ApplySplitPosition();
else if (this.splitSize != this.initTargetSize)
this.SplitPosition = this.initTargetSize;
this.anchor = Point.Empty;
}
private void SplitMove(int x, int y)
{
int splitSize = this.GetSplitSize((x - base.Left) + this.anchor.X, (y - base.Top) + this.anchor.Y);
if (this.splitSize != splitSize)
{
this.splitSize = splitSize;
this.DrawSplitBar(2);
}
}
public override string ToString()
{
string str = base.ToString();
string[] textArray1 = new string[] { str, ", MinExtra: ", this.MinExtra.ToString(CultureInfo.CurrentCulture), ", MinSize: ", this.MinSize.ToString(CultureInfo.CurrentCulture) };
return string.Concat(textArray1);
}
[DefaultValue(0)]
[Category("Appearance")]
[Description("The border type of the control.")]
public System.Windows.Forms.BorderStyle BorderStyle
{
get
{
return this.borderStyle;
}
set
{
if (!IsEnumValid(value, (int)value, 0, 2))
throw new InvalidEnumArgumentException("value", (int)value, typeof(System.Windows.Forms.BorderStyle));
if (this.borderStyle != value)
{
this.borderStyle = value;
base.UpdateStyles();
}
}
}
protected override System.Windows.Forms.CreateParams CreateParams
{
get
{
System.Windows.Forms.CreateParams createParams = base.CreateParams;
createParams.ExStyle &= -513;
createParams.Style &= -8388609;
System.Windows.Forms.BorderStyle borderStyle = this.borderStyle;
if (borderStyle != System.Windows.Forms.BorderStyle.FixedSingle)
{
if (borderStyle == System.Windows.Forms.BorderStyle.Fixed3D)
{
createParams.ExStyle |= 0x200;
}
return createParams;
}
createParams.Style |= 0x800000;
return createParams;
}
}
protected override Cursor DefaultCursor
{
get
{
switch (this.Dock)
{
case DockStyle.Top:
case DockStyle.Bottom:
return Cursors.HSplit;
case DockStyle.Left:
case DockStyle.Right:
return Cursors.VSplit;
}
return base.DefaultCursor;
}
}
protected override System.Windows.Forms.ImeMode DefaultImeMode
{
get
{
return System.Windows.Forms.ImeMode.Disable;
}
}
protected override Size DefaultSize
{
get { return new Size(3, 3); }
}
[Localizable(true), DefaultValue(3)]
public override DockStyle Dock
{
get { return base.Dock; }
set
{
if (((value != DockStyle.Top) && (value != DockStyle.Bottom)) && ((value != DockStyle.Left) && (value != DockStyle.Right)))
throw new ArgumentException("Splitter control must be docked left, right, top, or bottom.");
int splitterThickness = this.splitterThickness;
base.Dock = value;
switch (this.Dock)
{
case DockStyle.Top:
case DockStyle.Bottom:
if (this.splitterThickness == -1)
break;
base.Height = splitterThickness;
return;
case DockStyle.Left:
case DockStyle.Right:
if (this.splitterThickness != -1)
base.Width = splitterThickness;
break;
default:
return;
}
}
}
private bool Horizontal
{
get
{
DockStyle dock = this.Dock;
if (dock != DockStyle.Left)
return (dock == DockStyle.Right);
return true;
}
}
[Category("Behavior")]
[Localizable(true)]
[DefaultValue(25)]
[Description("Specifies the minimum size of the undocked area.")]
public int MinExtra
{
get { return this.minExtra; }
set
{
if (value < 0)
value = 0;
this.minExtra = value;
}
}
[Category("Behavior")]
[Localizable(true)]
[DefaultValue(25)]
[Description("Specifies the minimum size of the control being resized.")]
public int MinSize
{
get { return this.minSize; }
set
{
if (value < 0)
value = 0;
this.minSize = value;
}
}
[Category("Layout")]
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Description("The current position of the splitter, or -1 if it is not bound to a control.")]
public int SplitPosition
{
get
{
if (this.splitSize == -1)
{
this.splitSize = this.CalcSplitSize();
}
return this.splitSize;
}
set
{
SplitData data = this.CalcSplitBounds();
if (value > this.maxSize)
{
value = this.maxSize;
}
if (value < this.minSize)
{
value = this.minSize;
}
this.splitSize = value;
this.DrawSplitBar(3);
if (data.target == null)
{
this.splitSize = -1;
}
else
{
Rectangle bounds = data.target.Bounds;
switch (this.Dock)
{
case DockStyle.Top:
bounds.Height = value;
break;
case DockStyle.Bottom:
bounds.Y += bounds.Height - this.splitSize;
bounds.Height = value;
break;
case DockStyle.Left:
bounds.Width = value;
break;
case DockStyle.Right:
bounds.X += bounds.Width - this.splitSize;
bounds.Width = value;
break;
}
data.target.Bounds = bounds;
Application.DoEvents();
this.OnSplitterMoved(new SplitterEventArgs(base.Left, base.Top, base.Left + (bounds.Width / 2), base.Top + (bounds.Height / 2)));
}
}
}
private class SplitData
{
public int dockHeight = -1;
public int dockWidth = -1;
internal Control target;
}
private class SplitterMessageFilter : IMessageFilter
{
private MySplitter owner;
public SplitterMessageFilter(MySplitter splitter)
{
this.owner = splitter;
}
public bool PreFilterMessage(ref Message m)
{
if ((m.Msg < 0x100) || (m.Msg > 0x108))
{
return false;
}
if ((m.Msg == 0x100) && (((int)((long)m.WParam)) == 0x1b))
{
this.owner.SplitEnd(false);
}
return true;
}
}
private static bool IsEnumValid(Enum enumValue, int value, int minValue, int maxValue)
{
return ((value >= minValue) && (value <= maxValue));
}
}
public class MySplitterDesigner : ControlDesigner
{
public MySplitterDesigner() { base.AutoResizeHandles = true; }
private void DrawBorder(Graphics graphics)
{
Color white;
Control control = this.Control;
Rectangle clientRectangle = control.ClientRectangle;
if (control.BackColor.GetBrightness() < 0.5)
white = Color.White;
else
white = Color.Black;
using (Pen pen = new Pen(white))
{
pen.DashStyle = DashStyle.Dash;
clientRectangle.Width--;
clientRectangle.Height--;
graphics.DrawRectangle(pen, clientRectangle);
}
}
protected override void OnPaintAdornments(PaintEventArgs pe)
{
base.OnPaintAdornments(pe);
if (((MySplitter)base.Component).BorderStyle == BorderStyle.None)
this.DrawBorder(pe.Graphics);
}
protected override void WndProc(ref Message m)
{
if (m.Msg == 0x47)
this.Control.Invalidate();
base.WndProc(ref m);
}
}
Here is highlight form:
public class HighLight : Form
{
public HighLight()
{
FormBorderStyle = FormBorderStyle.None;
BackColor = Color.Black;
Opacity = 0;
ShowInTaskbar = false;
StartPosition = FormStartPosition.Manual;
}
protected override void OnDeactivate(EventArgs e)
{
base.OnDeactivate(e);
this.Hide();
}
private const int SW_SHOWNOACTIVATE = 4;
private const int HWND_TOPMOST = -1;
private const uint SWP_NOACTIVATE = 0x0010;
[DllImport("user32.dll", EntryPoint = "SetWindowPos")]
static extern bool SetWindowPos(int hWnd, int hWndInsertAfter,
int X, int Y, int cx, int cy, uint uFlags);
[DllImport("user32.dll")]
static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
public void ShowInactiveTopmost()
{
ShowWindow(this.Handle, SW_SHOWNOACTIVATE);
SetWindowPos(this.Handle.ToInt32(), HWND_TOPMOST,
this.Left, this.Top, this.Width, this.Height,
SWP_NOACTIVATE);
this.Opacity = 0.3;
}
}

How to implement movement in a chess game ?

I am learning to make a small variant of chess game using windows forms C#, the game includes only the pawns of both sides, i have drew the board and organized the pieces on there places, but i honestly do not know how to start implementing the moves by clicking the mouse on the piece and then the location where i want to move it.
as references the black pawn is named piece, and white pawn is named pieceW
here is my code for the board
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 AIchess
{
public partial class Form1 : Form
{
static System.Drawing.Bitmap piece = AIchess.Properties.Resources.piece;
ChessPiece Piece = new ChessPiece(piece, ChessColor.Black);
static System.Drawing.Bitmap pieceW = AIchess.Properties.Resources.pieceW;
ChessPiece PieceW = new ChessPiece(pieceW, ChessColor.White);
Square[,] square = new Square[8, 8];
public Form1()
{
InitializeComponent();
int i, j;
for (i = 0; i < 8; i++)
{
for (j = 0; j < 8; j++)
{
this.square[i, j] = new Square();
this.square[i, j].BackColor = System.Drawing.SystemColors.ActiveCaption;
this.square[i, j].BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.square[i, j].Location = new System.Drawing.Point(57 + i * 60, 109 + j * 60);
this.square[i, j].Name = i.ToString()+j.ToString();
this.square[i, j].Size = new System.Drawing.Size(60, 60);
this.square[i, j].TabIndex = 2;
this.square[i, j].TabStop = false;
this.Controls.Add(this.square[i, j]);
if (j == 1)
{
this.square[i, j].Image = piece;
this.square[i, j].AllocatedBy = "black";
}
if (j == 6)
{
this.square[i, j].Image = pieceW;
this.square[i, j].AllocatedBy = "white";
}
if (((i+j) % 2) ==0)
this.square[i, j].BackColor = Color.RoyalBlue;
else
this.square[i, j].BackColor = Color.LightBlue;
}
}
}
}
public enum ChessColor
{
White,
Black,
};
class ChessPiece
{
private Image DisplayedImage;
private ChessColor DisplayedColor;
private Point CurrentSquare;
public ChessPiece(Image image, ChessColor color)
{
DisplayedImage = image;
DisplayedColor = color;
}
}
class Square:PictureBox
{
private bool color;
public string AllocatedBy;
}
}
Here's a really simple implementation, I hope you won't mind that I did it from scratch.
Obviously it's very simple, there's no drag and drop and no animation but it fulfills your requirement.
I'll go through each part and explain them
InitializeGame
There you do set your images dimensions (they should be identical obviously)
You add in the dictionary the relationship between piece type/color and your bitmap
Note : the grid will be scaled so you can throw any size of bitmap you like
CreateBoard, DrawGame, DrawPieces
Nothing exceptional in there, note that for keeping things simple I do that every time a user clicks but it shouldn't be much of an issue, it's not Crysis after all :D
PickOrDropPiece
This is the logic where picking/dropping happens, it's really trivial and I'll let you take a look by yourself.
Differences between your code
I've created a Board type which holds the pieces and that you can easily update.
Note : do not remove the equality members in Piece they are here to help the dictionary.
Make sure to use 32-bit bitmaps with transparent borders
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
pictureBox1.MouseDown += pictureBox1_MouseDown;
}
#region Properties
private Board Board { get; set; }
private Piece CurrentPiece { get; set; }
private Dictionary<Piece, Bitmap> PieceBitmaps { get; set; }
private int TileWidth { get; set; }
private int TileHeight { get; set; }
#endregion
#region Events
private void Form1_Load(object sender, EventArgs e)
{
InitializeGame();
DrawGame();
}
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
PickOrDropPiece(e);
DrawGame();
}
#endregion
#region Methods
private void InitializeGame()
{
TileWidth = 64;
TileHeight = 64;
Board = new Board();
PieceBitmaps = new Dictionary<Piece, Bitmap>();
PieceBitmaps.Add(new Piece(PieceType.Pawn, PieceColor.Black), new Bitmap("pawnblack.png"));
PieceBitmaps.Add(new Piece(PieceType.Pawn, PieceColor.White), new Bitmap("pawnwhite.png"));
}
private void DrawGame()
{
var tileSize = new Size(TileWidth, TileHeight);
Bitmap bitmap = CreateBoard(tileSize);
DrawPieces(bitmap);
pictureBox1.Image = bitmap;
}
private Bitmap CreateBoard(Size tileSize)
{
int tileWidth = tileSize.Width;
int tileHeight = tileSize.Height;
var bitmap = new Bitmap(tileWidth*8, tileHeight*8);
using (Graphics graphics = Graphics.FromImage(bitmap))
{
for (int x = 0; x < 8; x++)
{
for (int y = 0; y < 8; y++)
{
Brush brush = (x%2 == 0 && y%2 == 0) || (x%2 != 0 && y%2 != 0) ? Brushes.Black : Brushes.White;
graphics.FillRectangle(brush, new Rectangle(x*tileWidth, y*tileHeight, tileWidth, tileHeight));
}
}
}
return bitmap;
}
private void DrawPieces(Bitmap bitmap)
{
using (Graphics graphics = Graphics.FromImage(bitmap))
{
Board board = Board;
for (int x = 0; x < 8; x++)
{
for (int y = 0; y < 8; y++)
{
Piece piece = board.GetPiece(x, y);
if (piece != null)
{
Bitmap bitmap1 = PieceBitmaps[piece];
graphics.DrawImageUnscaled(bitmap1, new Point(x*TileWidth, y*TileHeight));
}
}
}
}
}
private void PickOrDropPiece(MouseEventArgs e)
{
Point location = e.Location;
int x = location.X/TileWidth;
int y = location.Y/TileHeight;
bool pickOrDrop = CurrentPiece == null;
if (pickOrDrop)
{
// Pick a piece
Piece piece = Board.GetPiece(x, y);
Board.SetPiece(x, y, null);
if (piece != null)
{
label1.Text = string.Format("You picked a {0} {1} at location {2},{3}", piece.Color, piece.Type, x,
y);
}
else
{
label1.Text = "Nothing there !";
}
CurrentPiece = piece;
}
else
{
// Drop picked piece
Board.SetPiece(x, y, CurrentPiece);
label1.Text = string.Format("You dropped a {0} {1} at location {2},{3}", CurrentPiece.Color,
CurrentPiece.Type, x,
y);
CurrentPiece = null;
}
}
#endregion
}
public class Board
{
private readonly Piece[] _pieces;
public Board()
{
_pieces = new Piece[8*8];
PopulatePieces();
}
public Piece GetPiece(int x, int y)
{
int i = y*8 + x;
return _pieces[i];
}
public void SetPiece(int x, int y, Piece piece)
{
int i = y*8 + x;
_pieces[i] = piece;
}
private void PopulatePieces()
{
for (int i = 0; i < 8; i++)
{
SetPiece(i, 1, new Piece(PieceType.Pawn, PieceColor.Black));
SetPiece(i, 7, new Piece(PieceType.Pawn, PieceColor.White));
}
}
}
public class Piece
{
private readonly PieceColor _color;
private readonly PieceType _type;
public Piece(PieceType type, PieceColor color)
{
_type = type;
_color = color;
}
public PieceType Type
{
get { return _type; }
}
public PieceColor Color
{
get { return _color; }
}
protected bool Equals(Piece other)
{
return _color == other._color && _type == other._type;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != GetType()) return false;
return Equals((Piece) obj);
}
public override int GetHashCode()
{
unchecked
{
return ((int) _color*397) ^ (int) _type;
}
}
public static bool operator ==(Piece left, Piece right)
{
return Equals(left, right);
}
public static bool operator !=(Piece left, Piece right)
{
return !Equals(left, right);
}
}
public enum PieceType
{
Pawn
}
public enum PieceColor
{
Black,
White
}
}

Hide mouse cursor after an idle time

I want to hide my mouse cursor after an idle time and it will be showed up when I move the mouse. I tried to use a timer but it didn't work well. Can anybody help me? Please!
If you are using WinForms and will only deploy on Windows machines then it's quite easy to use user32 GetLastInputInfo to handle both mouse and keyboard idling.
public static class User32Interop
{
public static TimeSpan GetLastInput()
{
var plii = new LASTINPUTINFO();
plii.cbSize = (uint)Marshal.SizeOf(plii);
if (GetLastInputInfo(ref plii))
return TimeSpan.FromMilliseconds(Environment.TickCount - plii.dwTime);
else
throw new Win32Exception(Marshal.GetLastWin32Error());
}
[DllImport("user32.dll", SetLastError = true)]
static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);
struct LASTINPUTINFO
{
public uint cbSize;
public uint dwTime;
}
}
And then in your Form
public partial class MyForm : Form
{
Timer activityTimer = new Timer();
TimeSpan activityThreshold = TimeSpan.FromMinutes(2);
bool cursorHidden = false;
public Form1()
{
InitializeComponent();
activityTimer.Tick += activityWorker_Tick;
activityTimer.Interval = 100;
activityTimer.Enabled = true;
}
void activityWorker_Tick(object sender, EventArgs e)
{
bool shouldHide = User32Interop.GetLastInput() > activityThreshold;
if (cursorHidden != shouldHide)
{
if (shouldHide)
Cursor.Hide();
else
Cursor.Show();
cursorHidden = shouldHide;
}
}
}
Here is a contrived example of how to do it. You probably had some missing logic that was overriding the cursor's visibility:
public partial class Form1 : Form
{
public TimeSpan TimeoutToHide { get; private set; }
public DateTime LastMouseMove { get; private set; }
public bool IsHidden { get; private set; }
public Form1()
{
InitializeComponent();
TimeoutToHide = TimeSpan.FromSeconds(5);
this.MouseMove += new MouseEventHandler(Form1_MouseMove);
}
void Form1_MouseMove(object sender, MouseEventArgs e)
{
LastMouseMove = DateTime.Now;
if (IsHidden)
{
Cursor.Show();
IsHidden = false;
}
}
private void timer1_Tick(object sender, EventArgs e)
{
TimeSpan elaped = DateTime.Now - LastMouseMove;
if (elaped >= TimeoutToHide && !IsHidden)
{
Cursor.Hide();
IsHidden = true;
}
}
}
Need to account for Environment.Tickcount being negative:
public static class User32Interop
{
public static TimeSpan GetLastInput()
{
var plii = new LASTINPUTINFO();
plii.cbSize = (uint)Marshal.SizeOf(plii);
if (GetLastInputInfo(ref plii))
{
int idleTime = unchecked(Environment.TickCount - (int)plii.dwTime);
return TimeSpan.FromMilliseconds(idleTime);
}
else
throw new Win32Exception(Marshal.GetLastWin32Error());
}
[DllImport("user32.dll", SetLastError = true)]
static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);
struct LASTINPUTINFO
{
public uint cbSize;
public uint dwTime;
}
}
If you try to hide the cursor from another thread you need to call Invoke(...) on the winform to enter the UI thread. Had cost me some headegg why Cursor.Hide() wasn't working. Also "PInvoke ShowCursor(bool bShow)" has the benefit to return the Show/Hide-Count.
[DllImport("user32.dll")]
static extern int ShowCursor(bool bShow);
private System.Timers.Timer _timerMouseAutoHide;
Point _lastPos = new Point(int.MaxValue);
readonly Stopwatch _stopwatch = new Stopwatch();
private int _cursorVisibilityCount = 0;
private void InitMouseAutoHide()
{
if (_timerMouseAutoHide != null)
return;
_timerMouseAutoHide = new Timer(100){AutoReset = false};
_timerMouseAutoHide.Elapsed += MouseAutoHideHit;
_timerMouseAutoHide.Start();
_stopwatch.Restart();
}
private void MouseAutoHideHit(object pSender, ElapsedEventArgs pE)
{
try
{
if (IsDisposed)
return;
var lCurrentPos = Cursor.Position;
var lCursorHasMoved = _lastPos != lCurrentPos;
_lastPos = lCurrentPos;
if (_cursorVisibilityCount < 0 && lCursorHasMoved)
{
//Cursor is not Visible and Mouse has moved
_cursorVisibilityCount = ShowCursor();
Debug.WriteLine($"Visible {lCurrentPos}, ShowCursor={_cursorVisibilityCount}");
}
else if (_cursorVisibilityCount > -1 && _stopwatch.ElapsedMilliseconds > 3000)
{
//Cursor is Visible and Mouse didn't move fox x ms.
_cursorVisibilityCount = HideCursor();
Debug.WriteLine($"Hidden {lCurrentPos}, ShowCursor={_cursorVisibilityCount}");
}
if (lCursorHasMoved)
_stopwatch.Restart();
}
catch (Exception lEx)
{
GLog.Error(lEx);
}
finally
{
_timerMouseAutoHide?.Start();
}
}
public int ShowCursor()
{
var lCursorVisibilityCount = 0;
Invoke(new Action(() =>
{
do
{
lCursorVisibilityCount = ShowCursor(true);
} while (lCursorVisibilityCount < 0);
}));
return lCursorVisibilityCount;
}
public int HideCursor()
{
var lCursorVisibilityCount = 0;
Invoke(new Action(() =>
{
do
{
lCursorVisibilityCount = ShowCursor(false);
} while (lCursorVisibilityCount > -1);
}));
return lCursorVisibilityCount;
}

Categories

Resources