KeyDown functions not activating - c#

I've been making a game called dog simulator. Im at the point on where the movement needs to be developed, however, for some reason, the function didn't activate. Visual Studio (the IDE I use) said there were no errors. Some help will be appreciated
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 dog_simulator
{
public partial class Form1 : Form
{
bool right;
bool left;
public int left_var = 5;
public int right_var = 5;
public Form1()
{
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e)
{
}
public void button2_Click(object sender, EventArgs e)
{
panel1.Visible = false;
}
public void button1_Click(object sender, EventArgs e)
{
panel1.Visible = false;
}
public void Form1_KeyDown(object sender, KeyEventArgs e)
{
Console.WriteLine("Left has been pressed");
if (e.KeyCode == Keys.Left)
{
left = true;
Console.WriteLine("Left has been pressed");
}
if(e.KeyCode == Keys.Right)
{
right = true;
Console.WriteLine("Right has been pressed");
}
}
public void Form1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Left)
{
left = false;
Console.WriteLine("Left has been let go of");
}
if (e.KeyCode == Keys.Right)
{
right = false;
Console.WriteLine("Right has been let go of");
}
}
public void timer1_Tick(object sender, EventArgs e)
{
if (right == true)
{
player.Left += left_var;
}
if (left == true)
{
player.Left -= left_var;
}
Invalidate();
}
private void dog_Click(object sender, EventArgs e)
{
}
private void player_Click(object sender, EventArgs e)
{
}
private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
}
}
}

For a Windows Form to be able to see the key pressed you need to set the
this.KeyPreview = true;
in designer or in form code. Otherwise the key presses will be received by the control that has the current focus.
MSDN: Form.KeyPreview

Related

Problems with Image Tag in Picturebox

So, i try to learn how to Drag and Drop an Image from one PictureBox to another and that works well. But how can i drag and drop the Image TAG from pictureox1 to picturebox2?
i currently have 3 source images and 3 drop boxes.
the dropbox6 is locked with a countdown after a buttonclick (see button2)
(later i will lock all dropboxes)
after i hit this button a countdown starts and if the countdown is 0 (ZERO) only then i can drag one of the 3 images to this box.
however, i have given each of these 3 images in the souceboxes a TAG name.
how can i drop this tagname also to the dropbox?
here is what i have so far:
(the Label labeled "Counter" is actually Label4 in the code
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 Game
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void pictureBox_MouseDown(object sender, MouseEventArgs e)
{
// pictureBox1.DoDragDrop(pictureBox1.Image, DragDropEffects.Copy);
((PictureBox)sender).DoDragDrop(((PictureBox)sender).Image, DragDropEffects.Copy);
}
private void Form1_Load(object sender, EventArgs e)
{
pictureBox4.AllowDrop = true;
pictureBox5.AllowDrop = true;
pictureBox6.AllowDrop = true;
pictureBox6.Enabled = false;
}
private void pictureBox4_DragEnter(object sender, DragEventArgs e)
{
if(e.Data.GetDataPresent(DataFormats.Bitmap))
{
e.Effect = DragDropEffects.Copy;
}
}
private void pictureBox4_DragLeave(object sender, EventArgs e)
{
}
private void pictureBox4_DragDrop(object sender, DragEventArgs e)
{
Image getPicture = (Bitmap) e.Data.GetData(DataFormats.Bitmap);
pictureBox4.Image = getPicture;
}
private void pictureBox5_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.Bitmap))
{
e.Effect = DragDropEffects.Copy;
}
}
private void pictureBox5_DragLeave(object sender, EventArgs e)
{
}
private void pictureBox5_DragDrop(object sender, DragEventArgs e)
{
Image getPicture = (Bitmap)e.Data.GetData(DataFormats.Bitmap);
pictureBox5.Image = getPicture;
}
private void pictureBox6_DragDrop(object sender, DragEventArgs e)
{
Image getPicture = (Bitmap)e.Data.GetData(DataFormats.Bitmap);
pictureBox6.Image = getPicture;
timer1.Enabled = false;
}
private void pictureBox6_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.Bitmap))
{
e.Effect = DragDropEffects.Copy;
timer1.Enabled = false;
}
}
private void pictureBox6_DragLeave(object sender, EventArgs e)
{
timer1.Enabled = false;
}
private void pictureBox4_Click(object sender, EventArgs e)
{
MessageBox.Show("test");
}
private void timer1_Tick(object sender, EventArgs e)
{
counter--;
if (counter == 0)
timer1.Stop();
label4.Text = counter.ToString();
if(counter == 0)
{
pictureBox6.Enabled = true;
label4.Enabled = false;
timer1.Stop();
}
}
private void button1_Click(object sender, EventArgs e)
{
System.Windows.Forms.Application.Exit();
}
private void pictureBox6_Click(object sender, EventArgs e)
{
MessageBox.Show(pictureBox6.Tag.ToString());
}
private int counter = 3;
private void button2_Click(object sender, EventArgs e)
{
int counter = 3;
timer1 = new Timer();
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Interval = 1000; // 1 second
timer1.Start();
label4.Text = counter.ToString();
if(label4.Text == "0")
{
timer1.Stop();
}
pictureBox6.Image = Properties.Resources.shoreSite_d_1_l_x_x;
button2.Visible=false;
}
}
internal class bild1
{
private Bitmap shoreSite_d_1_l_x_x;
public bild1(Bitmap shoreSite_d_1_l_x_x)
{
this.shoreSite_d_1_l_x_x = shoreSite_d_1_l_x_x;
}
}
}
In MouseDown you are saying what you want to transmit in the DoDragDrop call. In your current case you are transmitting the image ((PictureBox)sender).Image but you can chose to transmit the tag as well...
private void pictureBox_MouseDown(object sender, MouseEventArgs e)
{
((PictureBox)sender).DoDragDrop(((PictureBox)sender).Image, DragDropEffects.Copy);
((PictureBox)sender).DoDragDrop(((PictureBox)sender).Tag, DragDropEffects.Copy);
}
...Then make sure to parse for each possible input type in DragDrop
private void pictureBox6_DragDrop(object sender, DragEventArgs e)
{
var image = e.Data.GetData(DataFormats.Bitmap) as Bitmap;
var tag = e.Data.GetData(DataFormats.Text) as string;
if (image != null)
{
pictureBox4.Image = image;
}
if (tag != null)
{
pictureBox4.Tag = tag;
}
timer1.Enabled = false;
}
Beware, that you will need to update all the code that checks that the data is Bitmap before it arrives at DragDrop ie in DragEnter and write code that handles both Bitmap and Text, otherwise the Drag functionality will break.
AWESOME!!
It works now. I will continue this Project.

I have a Modal Form ShowDialog I want to close the form if 1 push a button (works) 2 if a value changes in a static variable(doesn't work)

I have a form Modal ShowDialog. Trying the close the Form created if one of two things happen 1 button on the form is pushed or 2 a value changes in a static variable.So far the button works I can use another button to check the status of the value and view the change? How can I have the 2nd part close the form?
Main_Menu.cs
public void OverloadTripearly()
{
OverloadTripEarly overloadTripEarly = new OverloadTripEarly();
overloadTripEarly.Owner = this;
overloadTripEarly.ShowDialog();
// overloadTripEarly.Refresh();
// OLTrip = overloadTripEarly; // assign object to enter
}
OverloadTripEarly.cs code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WinFormTitlepageNew
{
public partial class OverloadTripEarly : Form
{
public OverloadTripEarly()
{
InitializeComponent();
}
private void btnOK_Click(object sender, EventArgs e)
{
if (backgroundWorker1.IsBusy)
{
backgroundWorker1.CancelAsync();
}
else
{
this.Close(); // close if button is pressed
this.Dispose();
}
}
private void OverloadTripEarly_Load(object sender, EventArgs e)
{
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
do
{
Thread.Sleep(100);
GlobalVariables.OverloadTest = NIDMMPXIeSlot5ConsoleApplication.SingleResistance
MeasurementApp();
if (double.IsNaN(GlobalVariables.OverloadTest))
{
GlobalVariables.OverloadFlag = true;
this.Close();
e.Cancel = true;
}
if (backgroundWorker1.CancellationPending)
{
e.Cancel = true;
this.Close();
return;
}
} while (double.IsNaN(GlobalVariables.OverloadTest));
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
}
private void backgroundWorker1_RunWorkerCompleted(object sender,
RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
{ this.Close();
this.Dispose();
}
}
private void button1_Click(object sender, EventArgs e)
{
GlobalVariables.OverloadTest = NIDMMPXIeSlot5ConsoleApplication.SingleResistance
MeasurementApp();
if (double.IsNaN(GlobalVariables.OverloadTest))
{
textBox1.Text = "NaN".ToString();
}
else
{ textBox1.Text = GlobalVariables.OverloadTest.ToString(); }
}
}
}
i think your Problem is, that you change the 'Win Form' from another thread.
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
{ this.Close();
this.Dispose();
}
}
Backgroundworker is calling from another thread. So you have to check if InvokeIsRequired and if so then invoke the this.Close()
check this link

How To make Mouse Click for new position

i already make a simple program to recording mouse position and playback. Now i wanna add event if the mouse left click and right mouse click. But i still not understand how to do it. I already try code from many site, but still not work. Any one wanna help me please ? I'm still learning about programing, i just wanna make simple program.
this is my code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AutoClicker
{
public partial class Form1 : Form
{
ListViewItem lv;
int a, b;
public Form1()
{
InitializeComponent();
this.Closing += new System.ComponentModel.CancelEventHandler(this.FormClosingEventCancle_Closing); //Menangkap event x di klik
}
private void FormClosingEventCancle_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
DialogResult dr = MessageBox.Show("Yakin ingin keluar?", "Konfirmasi", MessageBoxButtons.YesNo); if (dr == DialogResult.No)
e.Cancel = true;
else
e.Cancel = false;
}
private void button1_Click(object sender, EventArgs e)
{
timer1.Start();
btn_putar.Enabled = false;
btn_rekam.Enabled = false;
btn_berhenti.Enabled = true;
}
private void timer2_Tick(object sender, EventArgs e)
{
//set posisi baru mouse
if (a != b)
{
Cursor.Position = new Point(int.Parse(listView1.Items[a].SubItems[0].Text), int.Parse(listView1.Items[a].SubItems[1].Text));
a++;
}
//agar bisa rekam ulang dan data di set ulang
else
{
btn_rekam.Enabled = true;
btn_putar.Enabled = false;
btn_berhenti.Enabled = false;
listView1.Clear();
a = 0;
b = 0;
timer2.Stop();
}
}
private void timer1_Tick(object sender, EventArgs e)
{
lv = new ListViewItem(Cursor.Position.X.ToString());
lv.SubItems.Add(Cursor.Position.Y.ToString());
listView1.Items.Add(lv);
b++;
}
private void btn_berhenti_Click(object sender, EventArgs e)
{
btn_rekam.Enabled = true;
btn_putar.Enabled = true;
timer1.Stop();
timer2.Stop();
}
private void btn_putar_Click(object sender, EventArgs e)
{
timer2.Start();
btn_putar.Enabled = false;
btn_rekam.Enabled = false;
btn_berhenti.Enabled = false;
}
private void Form1_Load(object sender, EventArgs e)
{
a = 0;
b = 0;
btn_berhenti.Enabled = false;
btn_putar.Enabled = false;
}
}
}
You can use some of Mouse events like MouseClick, MouseDown, MouseUp, etc.
For example:
protected override void OnMouseDown(MouseEventArgs e)
{
if(e.Button == System.Windows.Forms.MouseButtons.Left)
{
//Do some stuff
MessageBox.Show("Lefty!");
}
else if(e.Button == System.Windows.Forms.MouseButtons.Right)
{
//Do some stuff
MessageBox.Show("Righty!");
}
}
Assuming you copy/pase this code somewhere in Form1 class, it will override Form1's OnMouseDown event.
When you left/right click on form, you'll get related MessageBox.
If you want to use the event on any other Control, you need to override that control's related event.
*Edit after comment:
public void OnMouseDown(object sender, MouseEventArgs e)
{
if(e.Button == System.Windows.Forms.MouseButtons.Left)
{
//Do some stuff
MessageBox.Show("Lefty!");
}
else if(e.Button == System.Windows.Forms.MouseButtons.Right)
{
//Do some stuff
MessageBox.Show("Righty!");
}
}
And add OnMouseDown event to any Control on form load. For example:
private void Form1_Load(object sender, EventArgs e)
{
a = 0;
b = 0;
button1.MouseDown += OnMouseDown;
listView1.MouseDown += OnMouseDown;
}
That way, when you left/right click on button1 or listView1 you will get a MessageBox.
You can setup an event handler to fire whenever the mouse button is clicked (shown below;)
namespace MouseClickDemo
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
MouseClick += Form1_MouseClick;
}
private void Form1_MouseClick(object sender, MouseEventArgs e)
{
if(e.Button == MouseButtons.Left)
{
//Left mouse button hit
}
if(e.Button == MouseButtons.Right)
{
//Right mouse button hit
}
}
}

How do I make it so I don't have to reclick an application for a keydown function to work?

Something has been really bothering me and its that the fact I have to click out and click back in the application for a key down function to work. Is there any way to fix it?
Code just in case if you need it:
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 dog_simulator
{
public partial class Form1 : Form
{
public bool KeyPreview { get; set; }
bool right;
bool left;
bool up;
bool down;
public int left_var = 5;
public int right_var = 5;
public Form1()
{
this.KeyPreview = true;
InitializeComponent();
Pee.Left += 220;
}
private void label1_Click(object sender, EventArgs e)
{
}
public void button2_Click(object sender, EventArgs e)
{
panel1.Visible = false;
}
public void button1_Click(object sender, EventArgs e)
{
panel1.Visible = false;
}
public void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Left)
{
left = true;
Console.WriteLine("Left has been pressed");
}
if(e.KeyCode == Keys.Right)
{
right = true;
Console.WriteLine("Right has been pressed");
}
if(e.KeyCode == Keys.Up)
{
up = true;
Console.WriteLine("Up has been pressed");
}
if(e.KeyCode == Keys.Down)
{
down = true;
Console.WriteLine("Down has been pressed");
}
}
public void Form1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Left)
{
left = false;
Console.WriteLine("Left has been let go of");
}
if (e.KeyCode == Keys.Right)
{
right = false;
Console.WriteLine("Right has been let go of");
}
if (e.KeyCode == Keys.Up)
{
up = false;
Console.WriteLine("Up has been let go of");
}
if (e.KeyCode == Keys.Down)
{
down = false;
Console.WriteLine("Down has been let go of");
}
}
public void timer1_Tick(object sender, EventArgs e)
{
if (right == true)
{
player.Left += left_var;
}
if (left == true)
{
player.Left -= left_var;
}
Invalidate();
if (up == true)
{
player.Top -= left_var;
}
if (down == true)
{
player.Top += left_var;
}
}
private void dog_Click(object sender, EventArgs e)
{
}
private void player_Click(object sender, EventArgs e)
{
}
private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
}
private void PeeTime_Tick(object sender, EventArgs e)
{
if(panel1.Visible == false)
{
Pee.Left -= 5;
if (Pee.Bounds.IntersectsWith(pee2.Bounds))
{
Pee.Left += 220;
}
}
}
}
}

Determining Button State from a separate class

I am having another issue writing my chip8 Emu. I have managed to get all instructions working aside from those that require input or those that involve graphics.
I am trying to write a seperate class to simply determine whether a button is being pressed or not. I have been working on this for some time and I think that I must be missing something very simple or I do not understand something conceptually. Here is the class I am writing with the exact errors in the comments
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WindowsFormsApplication1
{
class userIn
{
bool pressed = false;
public userIn()
{
}
public bool checkPress() //Error 9 'WindowsFormsApplication1.userIn.checkPress()': not all code paths return a value C
{ //<---- it is teling me that a closing bracket is expected here?
private void key5_Click(object sender, EventArgs e)
{
pressed = true;
}
private void keyb_Click(object sender, EventArgs e)
{
pressed = true;
}
private void key0_Click(object sender, EventArgs e)
{
pressed = true;
}
private void keya_Click(object sender, EventArgs e)
{
pressed = true;
}
private void keye_Click(object sender, EventArgs e)
{
pressed = true;
}
private void key9_Click(object sender, EventArgs e)
{
pressed = true;
}
private void key8_Click(object sender, EventArgs e)
{
pressed = true;
}
private void key7_Click(object sender, EventArgs e)
{
pressed = true;
}
private void keyd_Click(object sender, EventArgs e)
{
pressed = true;
}
private void keyf_Click(object sender, EventArgs e)
{
pressed = true;
}
private void key6_Click(object sender, EventArgs e)
{
pressed = true;
}
private void key4_Click(object sender, EventArgs e)
{
pressed = true;
}
private void keyc_Click(object sender, EventArgs e)
{
pressed = true;
}
private void key3_Click(object sender, EventArgs e)
{
pressed = true;
}
private void key2_Click(object sender, EventArgs e)
{
pressed = true;
}
private void key1_Click(object sender, EventArgs e)
{
pressed = true;
}
return pressed; //Error 6 Invalid token 'return' in class, struct, or interface member declaration
}
}
} // Error 8 Type or namespace definition, or end-of-file expected
Last line would not fit in the box
Does anyone have any Ideas or suggestions?
As always any help is appreciated!
} for checkPress method comes in end of class, your correct method:
public bool checkPress()
{
return pressed;
}
and your code should be like this:
using System;
...
namespace WindowsFormsApplication1
{
class userIn
{
bool pressed = false;
public userIn()
{
}
public bool checkPress() // This method
{
return pressed;
} // Must close here, not end of class
.
.
.
private void key1_Click(object sender, EventArgs e)
{
pressed = true;
}
}
}
If a button is belong to class XXX then you can expose its state by create a read-only property. It is not a good idea to create another class that depends on internal-implementation of XXX.
Short answer:
You have opened a method inside of another method.
Long answer
The following is your code properly indented (I recomend you AStyle for that):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WindowsFormsApplication1
{
class userIn
{
bool pressed = false;
public userIn()
{
}
public bool checkPress() //Error 9 'WindowsFormsApplication1.userIn.checkPress()': not all code paths return a value C
{ //<---- it is teling me that a closing bracket is expected here?
private void key5_Click(object sender, EventArgs e)
{
pressed = true;
}
private void keyb_Click(object sender, EventArgs e)
{
pressed = true;
}
private void key0_Click(object sender, EventArgs e)
{
pressed = true;
}
private void keya_Click(object sender, EventArgs e)
{
pressed = true;
}
private void keye_Click(object sender, EventArgs e)
{
pressed = true;
}
private void key9_Click(object sender, EventArgs e)
{
pressed = true;
}
private void key8_Click(object sender, EventArgs e)
{
pressed = true;
}
private void key7_Click(object sender, EventArgs e)
{
pressed = true;
}
private void keyd_Click(object sender, EventArgs e)
{
pressed = true;
}
private void keyf_Click(object sender, EventArgs e)
{
pressed = true;
}
private void key6_Click(object sender, EventArgs e)
{
pressed = true;
}
private void key4_Click(object sender, EventArgs e)
{
pressed = true;
}
private void keyc_Click(object sender, EventArgs e)
{
pressed = true;
}
private void key3_Click(object sender, EventArgs e)
{
pressed = true;
}
private void key2_Click(object sender, EventArgs e)
{
pressed = true;
}
private void key1_Click(object sender, EventArgs e)
{
pressed = true;
}
return pressed; //Error 6 Invalid token 'return' in class, struct, or interface member declaration
}
}
} // Error 8 Type or namespace definition, or end-of-file expected
Are you still unable to see the problem? Ok, here is a condensed version:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WindowsFormsApplication1
{
class userIn
{
bool pressed = false;
public userIn()
{
}
public bool checkPress() //Error 9 'WindowsFormsApplication1.userIn.checkPress()': not all code paths return a value C
{ //<---- it is teling me that a closing bracket is expected here?
private void key5_Click(object sender, EventArgs e)
{
pressed = true;
}
//And some other methods
return pressed; //Error 6 Invalid token 'return' in class, struct, or interface member declaration
}
}
} // Error 8 Type or namespace definition, or end-of-file expected
Does it look right to you?
Well, it just a way to put it, here is what the compiler sees:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WindowsFormsApplication1
{
class userIn
{
bool pressed = false;
public userIn()
{
}
public bool checkPress() //Error 9 'WindowsFormsApplication1.userIn.checkPress()': not all code paths return a value C
{ //<---- it is teling me that a closing bracket is expected here?
private void key5_Click(object sender, EventArgs e)
{
pressed = true;
}
//And some other methods
return pressed; //Error 6 Invalid token 'return' in class, struct, or interface member declaration
}
}
} // Error 8 Type or namespace definition, or end-of-file expected
Does it make sense now?
Chances are that you think the above code is right, if so this is not an answer... instead it is a question: What do you think you are trying to do?
Ok, yes, C# supports lambdas, are you trying to do the following?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WindowsFormsApplication1
{
class userIn
{
bool pressed = false;
public userIn()
{
}
public bool checkPress()
{
key5.Click += (sender, e) =>
{
pressed = true;
};
//And some other (anonymous) methods
return pressed;
}
}
}
But my instinct says that you just did some weird copy-paste and the intended code was like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WindowsFormsApplication1
{
class userIn
{
bool pressed = false;
public userIn()
{
}
public bool checkPress()
{
return pressed;
}
private void key5_Click(object sender, EventArgs e)
{
pressed = true;
}
//And some other methods
}
}
Make sense? I hope.

Categories