How to make popup form when enter and leave object? C# - c#

I am working on fitness project and need to creat a form with gif over text, when mouse is pointed on it and close popup when mouse leave it. In my case it works only one time. When pointing second time it returnes System.ObjectDisposedException "Access to the liquidated object is not possible"
Here is a code with text
namespace WindowsFormsApp1
{
public partial class Power : Form
{
public Power()
{
InitializeComponent();
}
public PopupDemo PopupDemo = null;
private void guna2CheckBox1_MouseHover(object sender, EventArgs e)
{
StartPopupDemo();
}
private void guna2CheckBox1_MouseLeave(object sender, EventArgs e)
{
PopupDemo.Close();
}
private void StartPopupDemo()
{
int MouseX = Cursor.Position.X;
int MouseY = Cursor.Position.Y;
PopupDemo = new PopupDemo();
PopupDemo.Show();
PopupDemo.Location = new Point(MouseX - PopupDemo.Width / 2, MouseY - PopupDemo.Height - 10);
}
}
}
Also i used nuget packages named Guna.
And ther is popup code
namespace WindowsFormsApp1
{
public partial class PopupDemo : Form
{
public PopupDemo()
{
InitializeComponent();
}
}
}
I hope there is more appropriate command instead of Close().
Help pls. If needed something else, just tell me. This is how it looks like

Related

I don't know how i can run a function continuously on xamarin

Hello this is my first time when i program in C# and first time when i use xamarin,and i maked this code on xamarin as a first project.
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace Counter
{
public partial class MainPage : ContentPage
{
private int count = 0;
private int squared = 0;
private double sqroot = 0;
private int milliseconds = 500;
private bool direction = true;
public MainPage()
{
InitializeComponent();
}
private void IncrementCounterClicked(object sender, EventArgs e)
{
direction = true;
}
private void Button_Clicked(object sender, EventArgs e)
{
direction = false;
}
private void Auto_increment()
{
if (direction == true)
count++;
else
count--;
squared = count * count;
sqroot = Math.Sqrt(count);
CounterLabel.Text = count.ToString();
Squared.Text = squared.ToString();
Sqroot.Text = sqroot.ToString();
Task.Delay(1000);
}
}
}
How can i run the function Auto_Increment every time the code executes?
I would use it on an android device, if it matters.
And also how i can display only first 2 digits of the double variable?
As far as I know If you want to use it for an android app which is build using xamarin you could actually use the lifecycle function given below:
protected override void OnResume()
{
#CALL_YOUR_FUNCTION_HERE
}
and to round the double values you could use the round method which is given below:
Math.Round(#Value_to_be_rounded, #number_of_decimal_places)
For instance: Math.Round(3.56, 1) will give you 3.5
Hope this helps.
Try doing this. Note that this solution isn't a good one. You have to control this infite loop in Auto_increment() or find another way to run it continiously in a cleaner way. Add a new button and replace the while(true) with while(yourBoolean) that you control by clicking the new button (like you already do for the increment.
public partial class MainPage : ContentPage
{
private int count = 0;
private int squared = 0;
private double sqroot = 0;
private int milliseconds = 500;
private bool direction = true;
public MainPage()
{
InitializeComponent();
Auto_increment();
}
private void IncrementCounterClicked(object sender, EventArgs e)
{
direction = true;
}
private void Button_Clicked(object sender, EventArgs e)
{
direction = false;
}
private void Auto_increment()
{
while (true) {
if (direction == true)
count++;
else
count--;
squared = count * count;
sqroot = Math.Sqrt(count);
CounterLabel.Text = count.ToString();
Squared.Text = squared.ToString();
Sqroot.Text = sqroot.ToString();
Task.Delay(1000);
}
}
}
PS : Also note that you should follow the Naming Guidelines in your code. In your case rename your private method AutoIncrement().
Hope this will help you.

Trying to use Debug.WriteLine to view what is being written to port. Getting error "Argument 1: cannot convert from 'method group' to 'string'

This is what it looks like so far:
The error is on line 31 "Debug.WriteLine(writeToPort);" Im basically want to see the data structure that is being sent over port
namespace MyProject
{
public partial class Form1 : Form
{
public Stopwatch watch { get; set; }
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
port.Open();
}
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
writeToPort(new Point(e.X, e.Y));
Debug.WriteLine(writeToPort);
}
public void writeToPort(Point coordinates)
}
port.Write(String.Format("X{0}Y{1}",
(coordinates.X / (Size.Width / 180)),
(coordinates.Y / (Size.Height / 180))));
}
}
}
Debug.WriteLine accepts a string. You are giving it a method. Since you don't have () on the method, it's not calling the method and using the return value, but you're passing a reference to the method itself, which doesn't work with Debug.WriteLine.
But writeToPort doesn't return a string either, so you just can't use it there.
If you want to see what was sent over the port, then you need to save what you're sending in its own variable and print that to the debug console. You can do it all in writeToPort, like this:
public void writeToPort(Point coordinates)
{
var stringToWrite = String.Format("X{0}Y{1}",
(coordinates.X / (Size.Width / 180)),
(coordinates.Y / (Size.Height / 180)))
port.Write(stringToWrite);
Debug.WriteLine(stringToWrite);
}

How to make an instance variables inside a class

I'm learning the Windows Application Form in Visual Studio, I'm making a number guessing game where the program generates a random number.
I put the random number generator inside the Button_Click method, I want the number to say the same when the program start but it change every time I click the button.
public partial class myWindow : Form
{
public myWindow()
{
InitializeComponent();
}
private void guessButton_Click(object sender, EventArgs e)
{
Random random = new Random();
int roll = random.Next(0, 99);
Where should I declare or put the random number generator and variable so it doesn't change ?
Make it a class member:
public partial class myWindow : Form
{
private int _roll;
private int _numGuesses;
public Window()
{
InitializeComponent();
Random random = new Random();
_roll = random.Next(0, 99);
}
private void guessButton_Click(object sender, EventArgs e)
{
bool isGuessCorrect = // Set this however you need to
if (isGuessCorrect)
{
// They got it right!
}
else
{
_numGuesses++;
if (_numGuesses > 9)
{
// Tell them they failed
}
else
{
// Tell them they're wrong, but have 10 - _numGuesses guesses left
}
}
}
}

Implementing double click event using timer

As I mentioned in this question, I am trying to implement a feature in my app whereby placing a cursor over some point for a while (say 3-5 seconds) triggers a double-click event. Based on the answers provided in that thread, I wrote the following. This code is not working as expected. Can someone please help?
#region Timer Mouse Double Click event
timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
//Here, the timer for Timer click event will start when mouse hovers over an area
private void form_MouseHover(object sender, System.EventArgs e)
{
timer.Start();
}
private void form_MouseLeave(object sender, System.EventArgs e)
{
timer.Stop();
}
void timer_Elapsed(object sender, ElapsedEventArgs e)
{
timer.Stop();
DoubleClickEvent();
}
//This method allows the user to click a file/folder by hovering/keeping still the mouse for specified time
void DoubleClickEvent()
{
DoClickMouse(0x2); // Left mouse button down
DoClickMouse(0x4); // Left mouse button up
}
static void DoClickMouse(int mouseButton)
{
var input = new INPUT()
{
dwType = 0, // Mouse input
mi = new MOUSEINPUT() { dwFlags = mouseButton }
};
if (SendInput(1, input, Marshal.SizeOf(input)) == 0)
{
throw new Exception();
}
}
[StructLayout(LayoutKind.Sequential)]
struct MOUSEINPUT
{
int dx;
int dy;
int mouseData;
public int dwFlags;
int time;
IntPtr dwExtraInfo;
}
struct INPUT
{
public uint dwType;
public MOUSEINPUT mi;
}
[DllImport("user32.dll", SetLastError = true)]
static extern uint SendInput(uint cInputs, INPUT input, int size);
#endregion
At first glance if your expecting a double click your are only doing a single click.
Down then up is one mouse click, shouldn't you do.
void DoubleClickEvent()
{
DoClickMouse(0x2); // Left mouse button down
DoClickMouse(0x4); // Left mouse button up
DoClickMouse(0x2); // Left mouse button down
DoClickMouse(0x4); // Left mouse button up
}
I hope it's not bad etiquette to provide two answers, however this is very different from my previous answer I felt editing for improvements wasn't correct.
By the looks of it you only have an event handler on the form, once you hover over a control on your form that will trigger your MouseLeave event of the form.
What you need is to add an event handler to every control on your form, something like this should do it.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
this.MouseHover += new EventHandler(MouseHoverEvent);
this.MouseLeave +=new EventHandler(MouseLeaveEvent);
timer1.Tick += new EventHandler(timer1_Tick);
foreach (Control item in this.Controls)
{
item.MouseHover += new EventHandler(MouseHoverEvent);
item.MouseLeave += new EventHandler(MouseLeaveEvent);
}
}
void timer1_Tick(object sender, EventArgs e)
{
timer1.Stop();
DoubleClickEvent();
}
void MouseLeaveEvent(object sender, EventArgs e)
{
timer1.Stop();
}
void MouseHoverEvent(object sender, EventArgs e)
{
timer1.Start();
}
}
It might be better to write this code as a single call to SendInput passing all the mouse downs and ups in one array. If you do this, SendInput guarantees that no other keys get in between the sequence. For example if a user has Alt + N keys held in theory it could sneak in - and change the auto-clicker clicking Yes to instead trigger a No (with a Alt + N keys held).
That being said however, I think the answer to our question is here: SendInput doesn't perform click mouse button unless I move cursor
Basic Idea:
I use MouseAdapter so that I don't have to override everything under the sun.
my MouseAdapter object has a MouseTimer which extends a swing Timer,
and an ActionListener with an overridden anonymous actionPerformed method.
I may have over thought/ or under thought when to start and stop the timer object.
Basically all it does is print out when it is single clicked or when it is double clicked.
package mouseUtils;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.Timer;
/**
*
* #author jcpartri
*/
public class MyMouseAdapter extends MouseAdapter{
private Integer mouseDoubleClickInterval = (int)
Toolkit.getDefaultToolkit().getDesktopProperty("awt.multiClickInterval");
private MouseEvent event = null;
private ActionListener taskPerformer = new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
if(event.getClickCount() == 2){
//mouseDoubleClicked(event);
mouseTimer.stop();
}
if(event.getClickCount() == 1){
//mouseSingleClicked(event);
mouseTimer.stop();
}
}
};
Class MouseTimer is a child of class Timer. When the Timer fires after a delay, there is a check to see if there was a single or double click within that timespan.
private MouseTimer mouseTimer = new
MouseTimer(getMouseDoubleClickInterval(),taskPerformer);
//The DebugClock helps me to see how long a process that I have programmed takes from
start to finish.
private DebugClock clock = new DebugClock();
//Constructors
public MyMouseAdapter(){
super();
}
#Override
public void mouseClicked(MouseEvent e){
event = e;
if(e.getClickCount() == 1){
mouseTimer.setInitialDelay(mouseDoubleClickInterval);
mouseTimer.start();
}
mouseTimer.setNumOfClicks();
}
public void mouseSingleClicked(MouseEvent e){
p("Mouse was SingleClicked!!!\n");
}
public void mouseDoubleClicked(MouseEvent e){
p("Mouse was DoubleClicked!!!\n");
}
#Override
public void mouseMoved(MouseEvent e){
event = e;
mouseTimer.resetNumOfClicks();
mouseTimer.stop();
}
//Setters and Getters for MouseAdapter
public Integer getMouseDoubleClickInterval(){
return this.mouseDoubleClickInterval;
}
//Timer Classes
private class MouseTimer extends Timer{
//Constructors
public MouseTimer(int delay, ActionListener taskPerformer){
super(delay,taskPerformer);
}
//Instance variables
private int numOfClicks = 0;
//Setters and Getters
public int getNumOfClicks(){
return this.numOfClicks;
}
public void setNumOfClicks(){
this.numOfClicks++;
}
public void resetNumOfClicks(){
this.numOfClicks = 0;
}
}
//Basic Printing Classes
private void p(String message){
System.out.print(message);
}
}
class DebugClock{
private long startTime = 0;
private long endTime = 0;
//Setters and Getters
public long getStartTime(){
return this.startTime;
}
public void setStartTime(long start){
this.startTime = start;
}
public long getEndTime(){
return this.endTime;
}
public void setEndTime(long end){
this.endTime = end;
}
//Constructors
public DebugClock(){
}
//Methods
public float getTimeInMilliSeconds(){
float seconds = (this.endTime - this.startTime);
return seconds;
}
}

TextBox not updating in C#

Specifically looking at the arrive method in the Customer class. I am using a for loop to create instances of the customer class, and when I try to write out their arrival times to a textBox (Just for testing purposes) the text box does not update. Why is this?
This is just a small simulation project for my Computing class. It is in its early stages, and is probably wrong in a lot of places!
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.Threading;
namespace QueueSimulation
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void Form1_Load(object sender, EventArgs e)
{
MessageBox.Show("The form has loaded");
}
public void goButton_Click(object sender, EventArgs e)
{
Initialisers init = new Initialisers();
Customer customer = new Customer();
customer.Arrive();
}
private void stopButton_Click(object sender, EventArgs e)
{
// put code here to break out of the program
}
}
public class Customer : Initialisers
{
int waitingTime;
int arrivalTime;
int arrivalInterval;
Initialisers init = new Initialisers();
public void Arrive()
{
Customer[] customer = new Customer[1000];
int counter = 0;
for (int i = 1; i <= 10; i++)
{
customer[i] = new Customer();
customer[i].TimeArrived();
displayArrival.Text = displayArrival.Text + customer[i].TimeArrived().ToString();
// Implement something to either show the time in the queue if needed
Thread.Sleep(init.CustomerArriveTime*100);
}
MessageBox.Show("All of the customers have arrived");
}
public string TimeArrived()
{
return Convert.ToString(DateTime.Now);
}
public void Leave()
{
}
public void GetServed()
{
}
}
public class Server
{
bool servingStatus;
int servingTime;
public void Serve()
{
}
}
public class Initialisers : Form1
{
private int cust_no = 3;
public int CustomerArriveTime
{
get
{
return cust_no;
}
set
{
cust_no = value;
}
}
private int s_time = 4;
public int serveTime
{
get
{
return s_time;
}
set
{
s_time = value;
}
}
}
}
Pass to the Arrive the instance of the textbox object created on your Form1.
public void Arrive(TextBox displayArrival)
Why are you inheriting the Form1 in Initialiserz? It's better to pass the reference to Form1 instead of inheritance in this case.
This seems overly complex. Try to model the real world. What is Initialisers, and why do you have an inheritance tree: Customer > Initialisers > Form1?
You're customer is writing to its own TextBox, instead of the TextBox you're looking at (the one from the Form that is visible).
Why not have a method Arrive that sets a private field to DateTime.Now. Then, ask the Customer its TimeArrived, which returns this field. In your Form, call these methods as much as needed in your loop.
This also seperaties command (Arrive) from query (TimeArrived) + keeps your inheritance more logical.
You might not even need Initialisers anymore. And don't let Customer inherit from Form, because a Customer isn't a Form.
I think there is more of a design issue here, you are creating instances of customer inside customer.
Your customer Arrive method should probably be a function inside the another class, like below, customer should just define what a customer is. Processing them should be handled by a different class.
class Customer
{
int waitingTime;
int arrivalTime;
int arrivalInterval;
// etc...
}
class ProcessCustomers
{
pubic void Arrive()
{
// etc...
}
}
public void goButton_Click(object sender, EventArgs e)
{
Initialisers init = new Initialisers();
ProcessCustomers CustomerQueue = new ProcessCustomers();
CustomerQueue .Arrive();
}
But for the text box issue you will have to expose a property in the form class and set it like that,
string ArrivalTime
{
get
{
return textBox1.Text;
}
set
{
textBox1.Text = value;
}
}

Categories