C# Secondary Monitor Bounds Issue - c#

I have made a bouncing screensaver in C#. When there is only a single monitor to display it works perfectly. However, when I have a dual monitor display the bounds do not work properly. The position of secondary monitor seems to have an effect and there does not seem to be a right bound (secondary screen is on the right side).
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace LIUScreensaver
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
if (args.Length > 0)
{
string firstArg = args[0].ToLower().Trim();
string secondArg = null;
//handle cases where arguments are separated by colon
if (firstArg.Length > 2)
{
secondArg = firstArg.Substring(3).Trim();
firstArg = firstArg.Substring(0, 2);
}
else if (args.Length > 1)
{
secondArg = args[1];
}
if (firstArg == "/c")
{
MessageBox.Show("This screensaver does not allow configuration changes");
}
else if (firstArg == "/p")
{
if (secondArg == null)
{
MessageBox.Show("Sorry, but there was an error.", "Screensaver", MessageBoxButtons.OK,
MessageBoxIcon.Error);
return;
}
IntPtr preview = new IntPtr(long.Parse(secondArg));
Application.Run(new ScreensaverForm(preview));
}
else if (firstArg == "/s")
{
ShowScreenSaver();
Application.Run();
}
else
{
MessageBox.Show("Invalid command line argument. \"" + firstArg + "\" is not a valid ", "Screensaver",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
else
{
MessageBox.Show("There has been an error displaying the screensaver. Please report this issue.");
}
}
public static void ShowScreenSaver()
{
//creates form on each display
int i = 0;
Screen[] screen = Screen.AllScreens;
for (i = 0; i < screen.Length; i++)
{
ScreensaverForm screensaver = new ScreensaverForm(screen[i].Bounds);
screensaver.Show();
}
}
}
}
//Screensaver form
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;
using System.Runtime.InteropServices;
namespace LIUScreensaver
{
public partial class ScreensaverForm : Form
{
[DllImport("user32.dll")]
static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);
[DllImport("user32.dll")]
static extern int SetWindowLong(IntPtr hWnd, int nIndex, IntPtr dwNewLong);
[DllImport("user32.dll", SetLastError = true)]
static extern int GetWindowLong(IntPtr hWnd, int nIndex);
[DllImport("user32.dll")]
static extern bool GetClientRect(IntPtr hWnd, out Rectangle lpRect);
private Boolean previewMode = false;
private int mouseX = 0, mouseY = 0;
private int imgX = 0, imgY = 0;
private Boolean bot = true, left = true, right = false, top = false;
Point p;
//constructor with no arguments
public ScreensaverForm()
{
InitializeComponent();
}
//constructor with bound arguments
public ScreensaverForm(Rectangle Bounds)
{
InitializeComponent();
this.Bounds = Bounds;
}
//preview constructor
public ScreensaverForm(IntPtr preview)
{
InitializeComponent();
SetParent(this.Handle, preview);
SetWindowLong(this.Handle, -16, new IntPtr(GetWindowLong(this.Handle, -16) | 0x40000000));
Rectangle parentRec;
GetClientRect(preview, out parentRec);
Size = parentRec.Size;
Location = new Point(0, 0);
txtLabel.Font = new System.Drawing.Font("Arial", 6);
previewMode = true;
}
//form load
private void ScreensaverForm_Load(object sender, EventArgs e)
{
Cursor.Hide();
TopMost = true;
System.Drawing.Color background = System.Drawing.ColorTranslator.FromHtml("#002668");
this.BackColor = background;
moveTimer.Interval = 1;
moveTimer.Tick += new EventHandler(moveTimer_Tick);
moveTimer.Start();
}
//
//-----------------------------------------------------------------------------------------------------
//The following code ends the application and exits the screensaver
private void ScreensaverForm_KeyPress(object sender, KeyPressEventArgs e)
{
if (!previewMode)
{
Application.Exit();
}
}
private void ScreensaverForm_MouseMove(object sender, MouseEventArgs e)
{
if (!previewMode)
{
if (mouseX == 0)
{
mouseX = e.X;
mouseY = e.Y;
}
if ((mouseX - e.X) > 5 || (mouseY - e.Y) > 5)
{
Application.Exit();
}
}
}
private void ScreensaverForm_MouseClick(object sender, MouseEventArgs e)
{
if (!previewMode)
{
Application.Exit();
}
}
//
//
//timer to bounce the image across the screen
private void moveTimer_Tick(object sender, System.EventArgs e)
{
// Move text to new location
bounce();
}
//function that moves the image
private void bounce()
{
//Checks boundaries
if (txtLabel.Location.Y + txtLabel.Image.Height - this.Bounds.Bottom>= 0)
{
top = true;
bot = false;
}
if (txtLabel.Location.X + txtLabel.Image.Width - this.Bounds.Right >= 0)
{
right = false;
left = true;
}
if (txtLabel.Location.X <= this.Bounds.Left)
{
right = true;
left = false;
}
if (txtLabel.Location.Y <= this.Bounds.Top)
{
top = false;
bot = true;
}
//moves image
if (bot == true)
{
if (right == true)
{
++imgX;
++imgY;
p.X = imgX;
p.Y = imgY;
txtLabel.Location = p;
}
else if (left == true)
{
--imgX;
++imgY;
p.X = imgX;
p.Y = imgY;
txtLabel.Location = p;
}
}
if (top == true)
{
if (right == true)
{
++imgX;
--imgY;
p.X = imgX;
p.Y = imgY;
txtLabel.Location = p;
}
else if (left == true)
{
--imgX;
--imgY;
p.X = imgX;
p.Y = imgY;
txtLabel.Location = p;
}
}
Invalidate();
}
}
}

The problem is the label's Location is its position relative to the monitor that it's on while the bounds you are comparing it too are an absolute position across all monitors.
So if the bounds of the primary monitor are Top: 0, Bottom: 900, Left: 0, Right: 1600
the bounds of the secondary monitor might be something like Top: 0, Bottom: 900, Left: 1600, Right: 3200. While the Location of the label on the secondary monitor will returning its position relative to the secondary monitor so for example Location.X: 200, Location.Y: 300.
You need to change the bounce Method to make the comparsion use either only absolute coordinates or only relative coordinates.
Here is the comparison code modified to use relative position of the label on the monitor;
if (txtLabel.Location.Y + txtLabel.Image.Height - (this.Bounds.Bottom - this.Bounds.Top) >= 0)
{
top = true;
bot = false;
}
if (txtLabel.Location.X + txtLabel.Image.Width - (this.Bounds.Right - this.Bounds.Left) >= 0)
{
right = false;
left = true;
}
// in relative coordinates left is always 0
if (txtLabel.Location.X <= 0)
{
right = true;
left = false;
}
// in relative coordinates top is always 0
if (txtLabel.Location.Y <= 0)
{
top = false;
bot = true;
}

Related

How can I use a tracbar to change a treeview nodes sizes and how to set the nodes text and red arrow to be fit the nodes changed size?

The treeview control code :
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;
public class AdvancedTreeView : TreeView
{
private const int TVM_SETEXTENDEDSTYLE = 0x1100 + 44;
private const int TVM_GETEXTENDEDSTYLE = 0x1100 + 45;
private const int TVS_EX_DOUBLEBUFFER = 0x0004;
[DllImport("user32.dll")]
private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp);
private Bitmap openedIcon, closedIcon;
private List<TreeNode> rootNodes = new List<TreeNode>();
public AdvancedTreeView()
{
DrawMode = TreeViewDrawMode.OwnerDrawText;
ShowLines = false;
AlternateBackColor = BackColor;
ArrowColor = SystemColors.WindowText;
this.AllowDrop = true;
}
public Color AlternateBackColor { get; set; }
public Color ArrowColor { get; set; }
protected override void OnHandleCreated(EventArgs e)
{
SendMessage(this.Handle, TVM_SETEXTENDEDSTYLE, (IntPtr)TVS_EX_DOUBLEBUFFER, (IntPtr)TVS_EX_DOUBLEBUFFER);
base.OnHandleCreated(e);
}
protected override void OnDrawNode(DrawTreeNodeEventArgs e)
{
Color backColor = (GetTopNodeIndex(e.Node) & 1) == 0 ? BackColor : AlternateBackColor;
using (Brush b = new SolidBrush(backColor))
{
e.Graphics.FillRectangle(b, new Rectangle(0, e.Bounds.Top, ClientSize.Width, e.Bounds.Height));
}
if ((e.State & TreeNodeStates.Selected) != 0)
{
e.Graphics.FillRectangle(Brushes.Green, e.Bounds);
}
// icon
if (e.Node.Nodes.Count > 0)
{
Image icon = GetIcon(e.Node.IsExpanded);
e.Graphics.DrawImage(icon, e.Bounds.Left - icon.Width - 3, e.Bounds.Top);
}
// text (due to OwnerDrawText mode, indenting of e.Bounds will be correct)
TextRenderer.DrawText(e.Graphics, e.Node.Text, Font, e.Bounds, ForeColor);
// indicate selection (if not by backColor):
if ((e.State & TreeNodeStates.Selected) != 0)
ControlPaint.DrawFocusRectangle(e.Graphics, e.Bounds);
}
protected override void OnItemDrag(ItemDragEventArgs e)
{
// Move the dragged node when the left mouse button is used.
if (e.Button == MouseButtons.Left)
{
DoDragDrop(e.Item, DragDropEffects.Move);
}
// Copy the dragged node when the right mouse button is used.
else if (e.Button == MouseButtons.Right)
{
DoDragDrop(e.Item, DragDropEffects.Copy);
}
}
protected override void OnDragOver(DragEventArgs e)
{
// Retrieve the client coordinates of the mouse position.
Point targetPoint = this.PointToClient(new Point(e.X, e.Y));
// Select the node at the mouse position.
this.SelectedNode = this.GetNodeAt(targetPoint);
}
protected override void OnDragDrop(DragEventArgs e)
{
Point targetPoint = PointToClient(new Point(e.X, e.Y));
TreeNode targetNode = GetNodeAt(targetPoint);
TreeNode draggedNode = (TreeNode)e.Data.GetData(typeof(TreeNode));
if (draggedNode == null || targetNode == null || draggedNode.Level != targetNode.Level)
{
return;
}
else
{
TreeNode parentNode = targetNode;
if (!draggedNode.Equals(targetNode) && targetNode != null)
{
bool canDrop = true;
while (canDrop && (parentNode != null))
{
canDrop = !Object.ReferenceEquals(draggedNode, parentNode);
parentNode = parentNode.Parent;
}
if (canDrop)
{
TreeNode treeNode = draggedNode.Parent;
if (treeNode != null)
{
int index = draggedNode.Index;
draggedNode.Remove();
treeNode.Nodes.Insert(targetNode.Index, draggedNode);
targetNode.Remove();
treeNode.Nodes.Insert(index, targetNode);
}
else
{
int draggedindex = draggedNode.Index;
int targetindex = targetNode.Index;
draggedNode.Remove();
targetNode.Remove();
this.Nodes.Insert(targetindex, draggedNode);
this.Nodes.Insert(draggedindex, targetNode);
}
}
}
}
SelectedNode = draggedNode;
}
private int GetTopNodeIndex(TreeNode node)
{
while (node.Parent != null)
node = node.Parent;
return Nodes.IndexOf(node);
}
// Determine whether one node is a parent
// or ancestor of a second node.
private bool ContainsNode(TreeNode node1, TreeNode node2)
{
// Check the parent node of the second node.
if (node2.Parent == null) return false;
if (node2.Parent.Equals(node1)) return true;
// If the parent node is not null or equal to the first node,
// call the ContainsNode method recursively using the parent of
// the second node.
return ContainsNode(node1, node2.Parent);
}
private Image GetIcon(bool nodeIsExpanded)
{
if (openedIcon == null)
InitIcons();
return nodeIsExpanded ? openedIcon : closedIcon;
}
private void InitIcons()
{
openedIcon = new Bitmap(16, 16);
closedIcon = new Bitmap(16, 16);
using (Brush b = new SolidBrush(ArrowColor))
{
using (Graphics g = Graphics.FromImage(openedIcon))
g.FillPolygon(b, new[] { new Point(0, 0), new Point(15, 0), new Point(8, 15), });
using (Graphics g = Graphics.FromImage(closedIcon))
g.FillPolygon(b, new[] { new Point(0, 0), new Point(15, 8), new Point(0, 15), });
}
}
}
And form1 where I'm adding the nodes and using the trackbar :
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 Treeview_Test
{
public partial class Form1 : Form
{
int numberofroots = 1000;
int childsnum = 50;
int childsnumperlevel = 5;
int leveldepth = 6;
public Form1()
{
InitializeComponent();
AddNodes();
for (int i = 0; i < 100; i++)
{
ComboboxItem boxitem = new ComboboxItem();
boxitem.Text = i.ToString();
comboBox1.Items.Add(boxitem);
}
comboBox1.SelectedIndex = 0;
}
private void AddNodes()
{
advancedTreeView1.Nodes.Clear();
for (int i = 0; i < numberofroots; i++)
{
TreeNode subnode = advancedTreeView1.Nodes.Add("New Node " + i);
if (allRootsWithChilds.Checked || i < childsnum)
{
for (int j = 0; j < leveldepth; j++)
{
// Add a new child node and set subnode to the new node we just added
subnode = subnode.Nodes.Add(subnode.Text);
for (int x = 0; x < childsnumperlevel; x++)
{
subnode.Nodes.Add("New Node " + x);
}
}
}
}
}
private void allRootsWithChilds_CheckedChanged(object sender, EventArgs e)
{
AddNodes();
}
private void advancedTreeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
textBox2.Text = e.Node.Text;
}
private void button1_Click(object sender, EventArgs e)
{
}
public class ComboboxItem
{
public string Text { get; set; }
public object Value { get; set; }
public override string ToString()
{
return Text;
}
}
private void trackBar1_Scroll(object sender, EventArgs e)
{
advancedTreeView1.ItemHeight = 5;
advancedTreeView1.SelectedNode.NodeFont = new Font("Arial", 5);
// Get the font size from combobox.
string selectedString = trackBar1.Value.ToString();//comboBox1.SelectedItem.ToString();
int myNodeFontSize = Int32.Parse(selectedString);
// Set the font of root node.
advancedTreeView1.SelectedNode.NodeFont = new Font("Arial", myNodeFontSize);
for (int i = 0; i < advancedTreeView1.Nodes[0].Nodes.Count; i++)
{
// Set the font of child nodes.
advancedTreeView1.Nodes[0].Nodes[i].NodeFont =
new Font("Arial", myNodeFontSize);
}
// Get the bounds of the tree node.
Rectangle myRectangle = advancedTreeView1.SelectedNode.Bounds;
int myNodeHeight = myRectangle.Height;
if (myNodeHeight < myNodeFontSize)
{
myNodeHeight = myNodeFontSize;
}
advancedTreeView1.ItemHeight = myNodeHeight + 4;
}
}
}
The first problem is each time I'm changing the trackBar value from 1 to 2 it's taking time the treeview to redraw. I'm not sure if it's drawing the whole treeview over again or only the nodes. Maybe the problem is the OnDrawNode override method in the AdvancedTreeView control code since this method is being called all the time.
The second problem is that when the nodes are resizing getting bigger each time when moving the trackBar to a higher value the text of the nodes is keep staying the same size and not resizing with the nodes. How can I make that the text of the nodes will be resized automatic fitting the size of the nodes?
And the red arrow the icon in the AdvancedTreeView code is also not fitting the nodes sizes the arrow is getting in each node higher and higher.
Here is a screenshot of the treeview when the trackbar value is 1: Now it's all fitting :
And this screenshot is after I moved the trackBar to the right to about the middle about value 50 :
Now the text is in the middle of each node but the text is still too small and not being resized with the nodes.
And the red arrow the icon in each node seems to be on the top left corner instead like in the first screenshot.
The icon/red arrow should also resize with the nodes and stay in the centre pointing the text of the nodes.
Edit :
Tried to reduce the code in the trackBar1_Scroll event to test and it sitll drawing slow when changing the trackBar values :
private void trackBar1_Scroll(object sender, EventArgs e)
{
// Get the font size from combobox.
string selectedString = trackBar1.Value.ToString();
int myNodeFontSize = Int32.Parse(selectedString);
// Get the bounds of the tree node.
Rectangle myRectangle = advancedTreeView1.SelectedNode.Bounds;
int myNodeHeight = myRectangle.Height;
if (myNodeHeight < myNodeFontSize)
{
myNodeHeight = myNodeFontSize;
}
advancedTreeView1.ItemHeight = myNodeHeight + 4;
}

Character walks slow in my C# game

The issue is I can't figure out why my character moves slow when I draw an image. All the timers are set to 1 interval and never changed. Any help would be greatly appreciated. Here is the entire project:
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 Rice_Boy_Tester_2
{
public partial class Form1 : Form
{
bool iggy = false;
bool left2 = false;
bool right2 = false;
bool Up2 = false;
bool Down2 = false;
bool Check2 = false;
bool left = false;
bool right = false;
bool Up = false;
bool Down = false;
bool Check = false;
public Form1() {
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) {
// Empty block
}
private void Refresh_Tick(object sender, EventArgs e) {
this.Refresh();
}
private void PriceBoyWalk_Tick(object sender, EventArgs e) {
if (left) // Goes Left
Player.Left -= 1;
if (Player.Left < 170 & Check == false) {
// Checks how far away player is from form
left = false;
Up = true;
}
if (Up & Player.Left < 170) { // Goes Up
Player.Top -= 1;
Check = true;
}
if (Player.Top < 100 & Check) {
Up = false;
Down = true;
}
if (right) // Goes Right
Player.Left += 1;
if (Down) // Goes Down
Player.Top += 1;
if (Player.Top + 150 > this.ClientSize.Height) {
Check = false;
Down = false;
right = true;
}
if (Player.Left + 150 > this.ClientSize.Width)
right = false;
}
private void B1_Click(object sender, EventArgs e) {
this.Paint += new PaintEventHandler(form1_Pad1_Rice);
RiceBoyWalkGif.Enabled = true;
left = true;
left2 = true;
RiceBoyWalk.Enabled = true;
}
private void timer1_Tick(object sender, EventArgs e) {
if (left2) {
Player.Image = Image.FromFile("Rice-Boy-Walking-Left-Bouncing.gif"); // Animates RiceBoyWalkingLeft
left2 = false;
}
if (Player.Left < 170 & Check2 == false) {
// Checks how far away the player is from form
left2 = false;
Up2 = true;
}
if (Up2 & Player.Left < 170) { // Goes Up
this.Player.Size = new System.Drawing.Size(36, 76); // Changes size of the picture box to maintain quality
Player.Image = Image.FromFile("Rice-Boy-Walking-Up-Bouncing.gif"); // Animates RiceBoyWalkingUp
Check2 = true;
Up2 = false;
}
if (Player.Top < 101 & Check2) {
// Player.Top < 101 must be +1 greater than the RiceBoyWalkTimer
Up2 = false;
Down2 = true;
}
if (right2) {
this.Player.Size = new System.Drawing.Size(53, 77); // Changes size of the picture box to maintain quality
Player.Image = Image.FromFile("Rice-Boy-Walking-Right-Bouncing.gif"); // Animates RiceBoyWalkingRight
right2 = false;
}
if (Down2) { // Goes Down
Player.Image = Image.FromFile("Rice-Boy-Walking-Down.gif");
Down2 = false;
}
if (Player.Top + 150 > this.ClientSize.Height) {
iggy = true; // Shows that riceboy is approaching the starting point
Check2 = false;
Down2 = false;
right2 = true;
}
if (Player.Left + 150 > this.ClientSize.Width & iggy) {
right2 = false;
Player.Image = Properties.Resources.Rice_Boy_Standing_Left;
}
}
private void form1_Pad1_Rice(object sender, System.Windows.Forms.PaintEventArgs e) {
e.Graphics.DrawImage(Properties.Resources.Corn_Cobs, 120, 58, 50, 50);
// Draws Corn cobs Character goes slower when corn is drawing
// (x(-left), y(-Up), W, H)
}
Start with this:
Player.Image = Image.FromFile("Rice-Boy-Walking-Down.gif");
(and the other load routines).
On every tick? Seriously?
Load them once during initialization, store them in variables, reuse the images. Ever played a computer game? They are not trashing your disc trying to load all graphics asset every frame.
Disc access is slow. Image decoding is slow. And I doubt you change the images while the program runs.

How can user resize control at runtime in winforms

Say i have a pictureBox.
Now what i want is that user should be able to resize the pictureBox at will. However i have no idea on how to even start on this thing. I have searched internet however information is scarce.
Can anybody at least guide me on where to start ?
This is pretty easy to do, every window in Windows has the innate ability to be resizable. It is just turned off for a PictureBox, you can turn it back on by listening for the WM_NCHITTEST message. You simply tell Windows that the cursor is on a corner of a window, you get everything else for free. You'll also want to draw a grab handle so it is clear to the user that dragging the corner will resize the box.
Add a new class to your project and paste the code shown below. Build + Build. You'll get a new control on top of the toolbox, drop it on a form. Set the Image property and you're set to try it.
using System;
using System.Drawing;
using System.Windows.Forms;
class SizeablePictureBox : PictureBox {
public SizeablePictureBox() {
this.ResizeRedraw = true;
}
protected override void OnPaint(PaintEventArgs e) {
base.OnPaint(e);
var rc = new Rectangle(this.ClientSize.Width - grab, this.ClientSize.Height - grab, grab, grab);
ControlPaint.DrawSizeGrip(e.Graphics, this.BackColor, rc);
}
protected override void WndProc(ref Message m) {
base.WndProc(ref m);
if (m.Msg == 0x84) { // Trap WM_NCHITTEST
var pos = this.PointToClient(new Point(m.LParam.ToInt32()));
if (pos.X >= this.ClientSize.Width - grab && pos.Y >= this.ClientSize.Height - grab)
m.Result = new IntPtr(17); // HT_BOTTOMRIGHT
}
}
private const int grab = 16;
}
Another very cheap way to get the resizing for free is by giving the control a resizable border. Which works on all corners and edges. Paste this code into the class (you don't need WndProc anymore):
protected override CreateParams CreateParams {
get {
var cp = base.CreateParams;
cp.Style |= 0x840000; // Turn on WS_BORDER + WS_THICKFRAME
return cp;
}
}
with use ControlMoverOrResizer class in this article you can do movable and resizable controls in run time just with a line of code! :) example:
ControlMoverOrResizer.Init(button1);
and now button1 is a movable and resizable control!
here is an article
http://www.codeproject.com/Articles/20716/Allow-the-User-to-Resize-Controls-at-Runtime
that should help you since it in vb here a C# translation
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
public class Form1
{
ResizeableControl rc;
private void Form1_Load(System.Object sender, System.EventArgs e)
{
rc = new ResizeableControl(pbDemo);
}
public Form1()
{
Load += Form1_Load;
}
}
AND RE-SIZE FUNCTION
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
public class ResizeableControl
{
private Control withEventsField_mControl;
private Control mControl {
get { return withEventsField_mControl; }
set {
if (withEventsField_mControl != null) {
withEventsField_mControl.MouseDown -= mControl_MouseDown;
withEventsField_mControl.MouseUp -= mControl_MouseUp;
withEventsField_mControl.MouseMove -= mControl_MouseMove;
withEventsField_mControl.MouseLeave -= mControl_MouseLeave;
}
withEventsField_mControl = value;
if (withEventsField_mControl != null) {
withEventsField_mControl.MouseDown += mControl_MouseDown;
withEventsField_mControl.MouseUp += mControl_MouseUp;
withEventsField_mControl.MouseMove += mControl_MouseMove;
withEventsField_mControl.MouseLeave += mControl_MouseLeave;
}
}
}
private bool mMouseDown = false;
private EdgeEnum mEdge = EdgeEnum.None;
private int mWidth = 4;
private bool mOutlineDrawn = false;
private enum EdgeEnum
{
None,
Right,
Left,
Top,
Bottom,
TopLeft
}
public ResizeableControl(Control Control)
{
mControl = Control;
}
private void mControl_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Left) {
mMouseDown = true;
}
}
private void mControl_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
{
mMouseDown = false;
}
private void mControl_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
{
Control c = (Control)sender;
Graphics g = c.CreateGraphics;
switch (mEdge) {
case EdgeEnum.TopLeft:
g.FillRectangle(Brushes.Fuchsia, 0, 0, mWidth * 4, mWidth * 4);
mOutlineDrawn = true;
break;
case EdgeEnum.Left:
g.FillRectangle(Brushes.Fuchsia, 0, 0, mWidth, c.Height);
mOutlineDrawn = true;
break;
case EdgeEnum.Right:
g.FillRectangle(Brushes.Fuchsia, c.Width - mWidth, 0, c.Width, c.Height);
mOutlineDrawn = true;
break;
case EdgeEnum.Top:
g.FillRectangle(Brushes.Fuchsia, 0, 0, c.Width, mWidth);
mOutlineDrawn = true;
break;
case EdgeEnum.Bottom:
g.FillRectangle(Brushes.Fuchsia, 0, c.Height - mWidth, c.Width, mWidth);
mOutlineDrawn = true;
break;
case EdgeEnum.None:
if (mOutlineDrawn) {
c.Refresh();
mOutlineDrawn = false;
}
break;
}
if (mMouseDown & mEdge != EdgeEnum.None) {
c.SuspendLayout();
switch (mEdge) {
case EdgeEnum.TopLeft:
c.SetBounds(c.Left + e.X, c.Top + e.Y, c.Width, c.Height);
break;
case EdgeEnum.Left:
c.SetBounds(c.Left + e.X, c.Top, c.Width - e.X, c.Height);
break;
case EdgeEnum.Right:
c.SetBounds(c.Left, c.Top, c.Width - (c.Width - e.X), c.Height);
break;
case EdgeEnum.Top:
c.SetBounds(c.Left, c.Top + e.Y, c.Width, c.Height - e.Y);
break;
case EdgeEnum.Bottom:
c.SetBounds(c.Left, c.Top, c.Width, c.Height - (c.Height - e.Y));
break;
}
c.ResumeLayout();
} else {
switch (true) {
case e.X <= (mWidth * 4) & e.Y <= (mWidth * 4):
//top left corner
c.Cursor = Cursors.SizeAll;
mEdge = EdgeEnum.TopLeft;
break;
case e.X <= mWidth:
//left edge
c.Cursor = Cursors.VSplit;
mEdge = EdgeEnum.Left;
break;
case e.X > c.Width - (mWidth + 1):
//right edge
c.Cursor = Cursors.VSplit;
mEdge = EdgeEnum.Right;
break;
case e.Y <= mWidth:
//top edge
c.Cursor = Cursors.HSplit;
mEdge = EdgeEnum.Top;
break;
case e.Y > c.Height - (mWidth + 1):
//bottom edge
c.Cursor = Cursors.HSplit;
mEdge = EdgeEnum.Bottom;
break;
default:
//no edge
c.Cursor = Cursors.Default;
mEdge = EdgeEnum.None;
break;
}
}
}
private void mControl_MouseLeave(object sender, System.EventArgs e)
{
Control c = (Control)sender;
mEdge = EdgeEnum.None;
c.Refresh();
}
}
Create a new c# winform application and paste this:
Don't forget to say thanks when it help you...
http://www.codeproject.com/script/Articles/ArticleVersion.aspx?aid=743923&av=1095793&msg=4778687
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 MyForm : Form
{
//Public Declaration:
double rW = 0;
double rH = 0;
int fH = 0;
int fW = 0;
// # Form Initialization
public MyForm()
{
InitializeComponent();
this.Resize += MyForm_Resize; // handles resize routine
this.tabControl1.Dock = DockStyle.None;
}
private void MyForm_Resize(object sender, EventArgs e)
{
rResize(this,true); //Call the routine
}
private void rResize(Control t, bool hasTabs) // Routine to Auto resize the control
{
// this will return to normal default size when 1 of the conditions is met
string[] s = null;
if (this.Width < fW || this.Height < fH)
{
this.Width = (int)fW;
this.Height = (int)fH;
return;
}
foreach (Control c in t.Controls)
{
// Option 1:
double rRW = (t.Width > rW ? t.Width / (rW) : rW / t.Width);
double rRH = (t.Height > rH ? t.Height / (rH) : rH / t.Height);
// Option 2:
// double rRW = t.Width / rW;
// double rRH = t.Height / rH;
s = c.Tag.ToString().Split('/');
if (c.Name == s[0].ToString())
{
//Use integer casting
c.Width = (int)(Convert.ToInt32(s[3]) * rRW);
c.Height = (int)(Convert.ToInt32(s[4]) * rRH);
c.Left = (int)(Convert.ToInt32(s[1]) * rRW);
c.Top = (int)(Convert.ToInt32(s[2]) * rRH);
}
if (hasTabs)
{
if (c.GetType() == typeof(TabControl))
{
foreach (Control f in c.Controls)
{
foreach (Control j in f.Controls) //tabpage
{
s = j.Tag.ToString().Split('/');
if (j.Name == s[0].ToString())
{
j.Width = (int)(Convert.ToInt32(s[3]) * rRW);
j.Height = (int)(Convert.ToInt32(s[4]) * rRH);
j.Left = (int)(Convert.ToInt32(s[1]) * rRW);
j.Top = (int)(Convert.ToInt32(s[2]) * rRH);
}
}
}
}
}
}
}
// # Form Load Event
private void MyForm_Load(object sender, EventArgs e)
{
// Put values in the variables
rW = this.Width;
rH = this.Height;
fW = this.Width;
fH = this.Height;
// Loop through the controls inside the form i.e. Tabcontrol Container
foreach (Control c in this.Controls)
{
c.Tag = c.Name + "/" + c.Left + "/" + c.Top + "/" + c.Width + "/" + c.Height;
// c.Anchor = (AnchorStyles.Right | AnchorStyles.Left );
if (c.GetType() == typeof(TabControl))
{
foreach (Control f in c.Controls)
{
foreach (Control j in f.Controls) //tabpage
{
j.Tag = j.Name + "/" + j.Left + "/" + j.Top + "/" + j.Width + "/" + j.Height;
}
}
}
}
}
}
}
Regards,
Kix46
namespace utils
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Data;
using System.Globalization;
using System.Xml;
using System.Text.RegularExpressions;
using System.Drawing;
public static class Helper
{
public const int WM_NCLBUTTONDOWN = 0xA1;
public const int HTCAPTION = 2;
public static int WS_THICKFRAME = 0x00040000;
public static int GWL_STYLE = -16;
public static int GWL_EXSTYLE = -20;
public static int WS_EX_LAYERED = 0x00080000;
public const int WS_RESIZABLE = 0x840000; //WS_BORDER + WS_THICKFRAME
[System.Runtime.InteropServices.DllImport("user32.dll")]
static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);
[System.Runtime.InteropServices.DllImport("user32.dll")]
static extern bool AppendMenu(IntPtr hMenu, uint uFlags, uint uIDNewItem, string lpNewItem);
[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern int GetWindowLong(IntPtr hWnd, int nIndex);
[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern int
SetLayeredWindowAttributes(IntPtr Handle, int Clr, byte transparency, int clrkey);
[System.Runtime.InteropServices.DllImport("shell32.dll")]
public static extern IntPtr ShellExecute(IntPtr hwnd, string lpOperation, string lpFile, string lpParameters, string lpDirectory, int nShowCmd);
[return: System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.Bool)]
[System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)]
public static extern bool PostMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);
[System.Runtime.InteropServices.DllImport("kernel32.dll")]
public static extern uint GetCurrentThreadId();
public static string ProcessException(this Exception ex)
{
StringBuilder strBuild = new StringBuilder(5000);
Exception inner = ex;
Enumerable.Range(0, 30).All(x =>
{
if (x == 0) strBuild.Append("########## Exception begin on thread id : " + GetCurrentThreadId().ToString() + " # :" + DateTime.Now.ToString() + " ##########\n");
strBuild.Append("---------------------[" + x.ToString() + "]---------------------\n");
strBuild.Append("Message : " + inner.Message + "\nStack Trace : " + inner.StackTrace + "\n");
strBuild.Append("---------------------[" + x.ToString() + "]---------------------\n");
inner = inner.InnerException;
if (inner == null)
{
strBuild.Append("########## Exception End on thread id : " + GetCurrentThreadId().ToString() + " # :" + DateTime.Now.ToString() + " ##########\n\n");
return false;
}
return true;
});
return strBuild.ToString();
}
public static void MakeResizable(this Panel pnl)
{
int dwCurStyle = Helper.GetWindowLong(pnl.Handle, GWL_STYLE);
dwCurStyle = dwCurStyle | Helper.WS_RESIZABLE;
Helper.SetWindowLong(pnl.Handle, GWL_STYLE, dwCurStyle);
}
}
protected override void OnLoad(EventArgs e)
{
imagePanel.MakeResizable();
base.OnLoad(e);
}
where imgPanel is some Panel in the WinForm App

Stack Overflow Exception (C#)

I'm currently working on a Snake game that can solve itself, but when I activate it, usually after 30~ successful hits, my application crashes with the aforementioned exception either in System.drawing.dll or in System.Windows.Forms.dll.
The problem usually occurs in the command "Application.DoEvents()", but it has occured in several other places too.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
using System.Threading;
using System.IO;
namespace Snake
{
enum Directions
{
Right = 1,
Left = -1,
Up = 2,
Down = -2,
NoDirection = 0
}
public partial class GameForm : Form
{
#region Data Members
SnakeGame gmGame;
Point pCurrFood;
Directions dirFirstDirection;
Directions dirSecondDirection;
Directions dirHelpDirection;
Color DEFAULT_COLOUR = Color.White;
const int SEGMENT_HEIGHT = 10;
const int SEGMENT_WIDTH = 10;
#endregion
#region Ctor
public GameForm()
{
InitializeComponent();
this.gmGame = new SnakeGame();
this.dirFirstDirection = Directions.NoDirection;
this.dirSecondDirection = Directions.NoDirection;
}
#endregion
#region Other Methods
private void PaintSegment(Graphics gGraphics, Point pnPoint, Color cColour)
{
Pen Pen = new Pen(cColour);
Rectangle Rectangle = new Rectangle(pnPoint.X,
pnPoint.Y,
SEGMENT_HEIGHT,
SEGMENT_WIDTH);
gGraphics.DrawRectangle(Pen, Rectangle);
Brush Brush = new SolidBrush(cColour);
gGraphics.FillRectangle(Brush, Rectangle);
}
private void PlaceNewFood()
{
Random rRand = new Random();
int nHeight = rRand.Next(this.panel1.Size.Height);
int nWidth = rRand.Next(this.panel1.Size.Width);
while ((nHeight % 10 != 0) || (nWidth % 10 != 0))
{
nHeight = rRand.Next(this.panel1.Size.Height - 10);
nWidth = rRand.Next(this.panel1.Size.Width - 10);
while (this.gmGame.SnakeQueue.Contains(new Point(nWidth, nHeight)))
{
nHeight = rRand.Next(this.panel1.Size.Height);
nWidth = rRand.Next(this.panel1.Size.Width);
}
}
this.pCurrFood = new Point(nWidth, nHeight);
this.PaintSegment(this.panel1.CreateGraphics(), this.pCurrFood, Color.Red);
}
private void SelfSolve()
{
this.dirFirstDirection = (Directions)(Math.Sign(this.gmGame.SnakeHead.Y -
this.pCurrFood.Y) * 2);
this.dirSecondDirection = (Directions)Math.Sign(this.pCurrFood.X -
this.gmGame.SnakeHead.X);
this.ManageSnake(this.dirFirstDirection, this.dirSecondDirection);
}
private bool WillCollide(Point pnPointToCheck)
{
return ((pnPointToCheck.X > this.panel1.Size.Width) ||
(pnPointToCheck.Y > this.panel1.Size.Height) ||
(pnPointToCheck.X * pnPointToCheck.Y < 0) ||
(this.gmGame.SnakeQueue.Contains(pnPointToCheck)));
}
private void ManageSnake(Directions dirFirstSnakeDirection,
Directions dirSecondSnakeDirection)
{
Point pnNewHead = this.gmGame.SnakeHead;
switch (dirFirstSnakeDirection)
{
case (Directions.Down):
{
if (this.WillCollide(new Point(pnNewHead.X, pnNewHead.Y + SEGMENT_HEIGHT)))
{
this.ManageSnake(Directions.NoDirection, dirSecondSnakeDirection);
}
else
{
pnNewHead.Y += SEGMENT_HEIGHT;
dirHelpDirection = Directions.Down;
}
break;
}
case (Directions.Up):
{
if (this.WillCollide(new Point(pnNewHead.X, pnNewHead.Y - SEGMENT_HEIGHT)))
{
this.ManageSnake(Directions.NoDirection, dirSecondSnakeDirection);
}
else
{
pnNewHead.Y -= SEGMENT_HEIGHT;
dirHelpDirection = Directions.Up;
}
break;
}
case (Directions.NoDirection):
{
switch (dirSecondSnakeDirection)
{
case (Directions.Right):
{
if (this.WillCollide(new Point(pnNewHead.X + SEGMENT_WIDTH, pnNewHead.Y)))
{
this.ManageSnake(this.dirHelpDirection, dirSecondSnakeDirection);
}
else
{
pnNewHead.X += SEGMENT_WIDTH;
}
break;
}
case (Directions.Left):
{
if (this.WillCollide(new Point(pnNewHead.X - SEGMENT_WIDTH, pnNewHead.Y)))
{
this.ManageSnake(this.dirHelpDirection, dirSecondSnakeDirection);
}
else
{
pnNewHead.X -= SEGMENT_WIDTH;
}
break;
}
}
break;
}
}
this.gmGame.AddSegment(pnNewHead);
if (this.gmGame.SnakeHead.Equals(this.pCurrFood))
{
this.lblScoreNum.Text = (int.Parse(this.lblScoreNum.Text) + 1).ToString();
this.PlaceNewFood();
}
else
{
this.PaintSegment(this.panel1.CreateGraphics(),
(Point)this.gmGame.SnakeQueue.Peek(),
DEFAULT_COLOUR);
this.gmGame.RemoveSegment();
}
this.PaintSegment(this.panel1.CreateGraphics(),
this.gmGame.SnakeHead,
Color.Green);
Thread.Sleep(5);
Application.DoEvents();
this.SelfSolve();
}
#endregion
#region Events
private void GameForm_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
this.PlaceNewFood();
this.SelfSolve();
}
else if (e.KeyCode == Keys.Escape)
{
this.Close();
}
else if (e.KeyCode == Keys.Space)
{
MessageBox.Show("Frozen, press OK to continue");
}
}
private void GameForm_ClientSizeChanged(object sender, EventArgs e)
{
this.PaintSegment(this.panel1.CreateGraphics(), new Point(210, 250), Color.Green);
this.PaintSegment(this.panel1.CreateGraphics(), new Point(220, 250), Color.Green);
this.PaintSegment(this.panel1.CreateGraphics(), new Point(230, 250), Color.Green);
this.PaintSegment(this.panel1.CreateGraphics(), new Point(240, 250), Color.Green);
this.PaintSegment(this.panel1.CreateGraphics(), new Point(250, 250), Color.Green);
}
#endregion
}
}
I know it's a lot of code, but since I'm not sure where's the root of the problem, I had to copy all of it.
I'd greatly appreciate it if you could point me in the right direction.
Thanks in advance :)
P.S. I know that the algorithm has flaws, I'll get to that later. Right now my main concern is solving the crash.
This is because you keep on going recursive in your method. e.g.:
Thread.Sleep(5);
Application.DoEvents();
this.SelfSolve();
Your method will basically never end.
You should use a timer and within that timer, call SelfSolve() This should solve your problem.
When using a timer you dont have to call DoEvents yourself since a winforms timer anyways posts a call to your method as a message and the message loop will handle the invocation and other messages.
SelfSolve should not call ManageSnake directly, but rather schedule its run for some later moment. Otherwise you get infinite recursion SelfSolve -> ManageSnake -> SelfSolve etc.

Label's position is different in xp and 7

I made small application(winforms) to show the cricket score (the world has just started , yay).
It works fine in xp, but in win 7 the label shows a few pixels down in position as compared to its position in xp, which totally ruins everything. ( i hope that was clear )
here is the exe: [REDACTED]
how it looks in xp; http://imgur.com/emcKG.jpg
how it looks in 7(approx): http://imgur.com/sdqry.jpg
also can someone confirm which .net my app requires ? I think its .net 2.0, since the target framework is set to .Net 2.0 .
Thanks
Edit: won't post the exe next time. sorry!
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net;
using System.Xml;
using System.Runtime.InteropServices;
using Microsoft.Win32;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
int numberOfMatches = 0;
int selectedmatch = 0;
string[,] data;
string fileToParse = Path.GetTempPath() + "cricketfile.xml";
int matchToShow = 0;
public const int WM_NCLBUTTONDOWN = 0xA1;
public const int HT_CAPTION = 0x2;
[DllImportAttribute("user32.dll")]
public static extern int SendMessage(IntPtr hWnd,
int Msg, int wParam, int lParam);
[DllImportAttribute("user32.dll")]
public static extern bool ReleaseCapture();
RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
public Form1()
{
InitializeComponent();
int X = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Width / 2 - this.Width / 2;
this.Location = new System.Drawing.Point(X, -5);
if (rkApp.GetValue("cricketscore") == null)
{
startWithWindowsToolStripMenuItem.Checked = false ;
}
else
{
startWithWindowsToolStripMenuItem.Checked = true ;
}
this.Region = new Region(new Rectangle(10, 10, 197, 17));
ToolTip tooltip = new ToolTip();
tooltip.SetToolTip(pictureBox1, " right click for settings, left click to move");
tooltip.SetToolTip(label1, " right click for settings, left click to move");
fetchData();
addContextEntries();
chooseIndia();
updateScore();
// MessageBox.Show(data.GetLength(0).ToString());
//foreach (string s in data)
//{
// Console.WriteLine(s);
//}
timer1.Interval = 10 * 1000;
timer1.Enabled = true;
}
public void addContextEntries()
{
// MessageBox.Show("num- " + numberOfMatches);
List<ToolStripMenuItem> Mylist1 = new List<ToolStripMenuItem>();
for (int i = 0; i < numberOfMatches; i++)
{
Mylist1.Add( new ToolStripMenuItem() );
this.contextMenuStrip1.Items.Add(Mylist1[i]);
Mylist1[i].Text = "See Match " + (i + 1) + "'s score";
switch(i)
{
case 0:
Mylist1[i].Click += new System.EventHandler(this.match1);
break;
case 1:
Mylist1[i].Click += new System.EventHandler(this.match2);
break;
case 2:
Mylist1[i].Click += new System.EventHandler(this.match3);
break;
case 3:
Mylist1[i].Click += new System.EventHandler(this.match4);
break;
case 4:
Mylist1[i].Click += new System.EventHandler(this.match5);
break;
}
}
}
public void match1(object sender, EventArgs e)
{
// MessageBox.Show("match 1");
matchToShow = 0;
label1.Text = data[0, 0] + " " + data[0, 1];
}
public void match2(object sender, EventArgs e)
{
// MessageBox.Show("match 2");
matchToShow = 1;
label1.Text = data[1, 0] + " " + data[1, 1];
}
public void match3(object sender, EventArgs e)
{
matchToShow = 2;
label1.Text = data[2, 0] + " " + data[2, 1];
}
public void match4(object sender, EventArgs e)
{
matchToShow = 3;
label1.Text = data[3, 0] + " " + data[3, 1];
}
public void match5(object sender, EventArgs e)
{
matchToShow = 4;
label1.Text = data[4, 0] + " " + data[4, 1];
}
public void chooseIndia()
{
for (int i = 0; i < data.GetLength(0); i++)
{
// MessageBox.Show("i - " + i);
if (data[i, 3].ToLower().Contains("australia"))
{
matchToShow = i;
// MessageBox.Show("i - " + i);
break;
}
}
}
public void updateScore()
{
fetchData();
//foreach (string s in data)
//{
// Console.WriteLine(s);
//}
// MessageBox.Show("matchToShow- " + matchToShow);
label1.Text = data[matchToShow,0] + " " + data[matchToShow ,1];
}
public void fetchData()
{
int matchnumber = -1;
numberOfMatches = 0;
WebClient Client = new WebClient();
try
{
Client.DownloadFile("http://synd.cricbuzz.com/score-gadget/gadget-scores-feed.xml", fileToParse);
}
catch ( WebException we)
{
if (we.ToString().ToLower().Contains("connect to"))
;//MessageBox.Show("unable to connect to server") ;
}
XmlTextReader xmlreader0 = new XmlTextReader(fileToParse);
while (xmlreader0.Read())
{
if (xmlreader0.Name.ToString() == "match" && xmlreader0.NodeType == XmlNodeType.Element)
{
++numberOfMatches;
}
}
data = new string[numberOfMatches, 4];
// numberOfMatches = 0;
// MessageBox.Show("matchnumbers - " + numberOfMatches);
XmlTextReader xmlreader = new XmlTextReader(fileToParse);
while (xmlreader.Read())
{
if (xmlreader.Name.ToString() == "header" && xmlreader.NodeType == XmlNodeType.Element)
{
xmlreader.Read();
data[matchnumber, 0] = xmlreader.Value;
// MessageBox.Show(xmlreader.Value);
}
if (xmlreader.Name == "description" && xmlreader.NodeType == XmlNodeType.Element)
{
// MessageBox.Show(xmlreader.Value);
xmlreader.Read();
// MessageBox.Show("matched - " + xmlreader.Value);
data[matchnumber, 1] = xmlreader.Value;
}
if (xmlreader.Name == "url-text" && xmlreader.NodeType == XmlNodeType.Element)
{
xmlreader.Read();
// MessageBox.Show(xmlreader.Value);
data[matchnumber, 2] = xmlreader.Value;
}
if (xmlreader.Name == "url-link" && xmlreader.NodeType == XmlNodeType.Element)
{
xmlreader.Read();
data[matchnumber, 3] = xmlreader.Value;
}
if (xmlreader.Name.ToString() == "match" && xmlreader.NodeType == XmlNodeType.Element)
{
matchnumber++;
}
}
xmlreader.Close();
xmlreader0.Close();
}
private void timer1_Tick(object sender, EventArgs e)
{
updateScore();
}
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
ReleaseCapture();
SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
}
}
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
ReleaseCapture();
SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
}
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void switchColrosToolStripMenuItem_Click(object sender, EventArgs e)
{
if ( label1.ForeColor == System.Drawing.Color.Black)
label1.ForeColor = System.Drawing.Color.White ;
else
label1.ForeColor = System.Drawing.Color.Black;
}
private void startWithWindowsToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void startWithWindowsToolStripMenuItem_CheckStateChanged(object sender, EventArgs e)
{
if (startWithWindowsToolStripMenuItem.Checked == true)
{
rkApp.SetValue("cricketscore", Application.ExecutablePath.ToString());
}
else
{
rkApp.DeleteValue("cricketscore", false);
}
}
private void showFullScorecardToolStripMenuItem_Click(object sender, EventArgs e)
{
System.Diagnostics.Process.Start(data[matchToShow, 3]);
}
private void label1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
ReleaseCapture();
SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
}
}
//public void findNumberOfMatches()
//{
// if (xmlreader.Name.ToString() == "match" && xmlreader.NodeType == XmlNodeType.Element)
// {
// matchnumber++;
// }
//}
}
}
btw how do I get by exe verified , so that normal people can use it without fear ? virustotal.com ?
Edit: oops , I was wrong ,tis not just the label. the picturebox to the left of the label has also been shifted down a few pixels.
It appears, from your screenshots, that the entire box that holds the text shrinks, and there's a blue bar that covers part of the label.
Perhaps it is a resolution issue or dpi issue. also they change color from one OS to the other??
You might need to set the locations and other properties in the code with a static ,hard coded values, rather than letting windows place it from the designer view or using some variable number based on the size of the screen
this is in c#.net should be similar
label1.Left = 10;
label1.Top = 10;
this.Region = new Region(new Rectangle(10, 10, 197, 17));
Delete that. It makes your window too small on a machine with a higher video dots-per-inch setting. Quite common on Win7. A higher DPI makes the fonts taller in pixels. The Form.AutoScaleMode property automatically adjusts for that by making the controls larger to fit that bigger font. Your Region doesn't grow though, cutting off the bottom of the controls. No idea why you use a Region in the first place since its a plain rectangle, I suppose you are looking for FormBorderStyle = None. A form won't allow you to make it too small but you can override that in the OnLoad method. Set the ClientSize large enough to fit the rescaled controls.
This has to do with a difference in the DPI settings on Windows XP and Windows 7.
How to change DPI on Windows 7.
How to change DPI on Windows XP.

Categories

Resources