Hide mouse cursor for specific time - c#

public partial class Form3 : Form
{
private readonly KeyboardHookListener m_KeyboardHookManager;
private readonly MouseHookListener m_MouseHookManager;
[DllImport("user32")]
private static extern Int32 ClipCursor(RECT lpRect);
[DllImport("user32")]
private static extern Int32 ShowCursor(Int32 bShow);
[DllImport("user32.dll")]
public static extern bool GetCursorPos(out POINT lpPoint);
[StructLayout(LayoutKind.Sequential)]
public struct POINT
{
public int X;
public int Y;
public static implicit operator Point(POINT point)
{
return new Point(point.X, point.Y);
}
}
public static Point GetCursorPosition()
{
POINT lpPoint;
GetCursorPos(out lpPoint);
//bool success = User32.GetCursorPos(out lpPoint);
// if (!success)
return lpPoint;
}
[StructLayout(LayoutKind.Sequential)]
private struct RECT
{
public Int32 Left;
public Int32 Top;
public Int32 Right;
public Int32 Bottom;
}
public Form3()
{
InitializeComponent();
m_KeyboardHookManager = new KeyboardHookListener(new GlobalHooker());
m_KeyboardHookManager.Enabled = true;
m_KeyboardHookManager.KeyDown += HookManager_KeyDown;
m_KeyboardHookManager.KeyUp += HookManager_KeyUp;
m_MouseHookManager = new MouseHookListener(new GlobalHooker());
m_MouseHookManager.Enabled = true;
m_MouseHookManager.MouseDown += HookManager_MouseDown;
m_MouseHookManager.MouseUp += HookManager_MouseUp;
}
private void Form3_Load(object sender, EventArgs e)
{
//ShowCursor(0);
//MoveCursor();
}
private void HookManager_KeyDown(object sender, KeyEventArgs e)
{
label1.Text = e.KeyData.ToString() + " Pressed";
}
private void HookManager_KeyUp(object sender, KeyEventArgs e)
{
label1.Text = e.KeyData.ToString() + " Released";
}
private void HookManager_MouseUp(object sender, MouseEventArgs e)
{
label1.Text = e.Button.ToString() + " Released";
}
private void HookManager_MouseDown(object sender, MouseEventArgs e)
{
label1.Text = e.Button.ToString() + " Pressed";
ShowCursor(0);
MoveCursor();
System.Threading.Thread.Sleep(5000);//5 sec
RestoreCursor(this);
ShowCursor(1);
}
private void button1_Click(object sender, EventArgs e)
{
//RestoreCursor(this);
//ShowCursor(1);
}
private void Form3_MouseMove(object sender, MouseEventArgs e)
{
//MoveCursor();
}
private RECT MouseTrap;
public void RestoreCursor(System.Windows.Forms.Form ThisForm)
{
var _with1 = MouseTrap;
_with1.Top = 0;
_with1.Left = 0;
_with1.Right = Screen.PrimaryScreen.Bounds.Width;
_with1.Bottom = Screen.PrimaryScreen.Bounds.Height;
ClipCursor(_with1);
}
private void MoveCursor()
{
// set the Current cursor, move the cursor's Position,
// and set its clipping rectangle to the form.
this.Cursor = new Cursor(Cursor.Current.Handle);
Cursor.Position = new Point(this.Left, this.Top);
Cursor.Clip = new Rectangle(this.Left, this.Top, this.Width, this.Height);
}
}
I am developing one sample application My requirement is when user clicks on anywhere on desktop for example click on Windows "Start" button then Hide the cursor for 2 sec then show the cursor after 2 sec at the same position.
For that I have written above code and used Thread.Sleep(2000) for waiting but cursor position restores to Form's left.
https://stackoverflow.com/questions/16781948/how-can-i-hook-globaly-all-the-keys-and-all-the-mouse-buttons/16782294
GlobalMouseHookDLL

you can achieve that using System.Windows.Forms.Timer.
Declare Timer on your form.
public partial class Form3 : Form
{
private Timer timer = new Timer();
Set it on Form_Load
timer.Enabled = false;
timer.Tick += Timer_Tick;
timer.Interval = 5000;
When user moves mouse, instead of Thread.Sleep activate timer. When timer ticks (when specified 5000 milliseconds pass), Timer_Tick method will execute. In it, show pointer.
private void HookManager_MouseDown(object sender, MouseEventArgs e)
{
label1.Text = e.Button.ToString() + " Pressed";
ShowCursor(0);
MoveCursor();
timer.Start();
}
private void Timer_Tick(object sender, EventArgs e)
{
RestoreCursor(this);
ShowCursor(1);
timer.Stop();
}

Related

How to make a label change its text every some time in C# windows forms

I have a label that I want to update every 5 seconds. It should change from 1921 to 1922 onward till 1992. I have tried using a timer but it gave me an error about being accessed on the wrong thread. The code I used was:
public partial class Form1 : Form
{
int x = 1921;
public Form1()
{
InitializeComponent();
}
System.Timers.Timer myTimer = new System.Timers.Timer(1000);
private void UpdateLabel(object sender, ElapsedEventArgs e)
{
label1.Text = x.ToString();
x += 1;
}
private void Form1_Load(object sender, EventArgs e)
{
myTimer.Elapsed += UpdateLabel;
myTimer.Start();
}
}
Try this:
private void UpdateLabel(object sender, ElapsedEventArgs e)
{
//Invoke makes the UI thread call the delegate.
Invoke((MethodInvoker)delegate {label1.Text = x.ToString(); });
x += 1;
}
try this
private readonly object y = new object();
int x = 1921;
public Form1()
{
InitializeComponent();
}
System.Timers.Timer myTimer = new System.Timers.Timer(1000);
private void UpdateLabel(object sender, ElapsedEventArgs e)
{
Invoke((MethodInvoker)(() => { lock (y) { label1.Text = x.ToString(); x++; } }));
}
private void Form1_Load(object sender, EventArgs e)
{
myTimer.Elapsed += UpdateLabel;
myTimer.Start();
}

combination of MouseDown and timer

I try to load a function like "holdFunction", during touching(MouseDown) and during at max 1 second .
So when user try to touch and hold for a second I have to call the function, and this isn't related to mouseUp.
Maybe I must to combine these:
private DateTime dtHold;
private void EditProduct_MouseDown(object sender, MouseButtonEventArgs e)
{
dtHold = DateTime.Now;
}
private void EditProduct_MouseUp(object sender, MouseButtonEventArgs e)
{
TimeSpan interval = TimeSpan.FromSeconds(1);
if (DateTime.Now.Subtract(dtHold) > interval)
{
//HoldFunction();
}
}
and
System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
private void EditProduct_MouseDown(object sender, MouseButtonEventArgs e)
{
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0, 0, 0,1,0);
dispatcherTimer.Start();
}
private int _sec = 0;
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
_sec = _sec + 1;
if (_sec == 2)
{
dispatcherTimer.Stop();
{
//HoldFunction();
}
_sec = 0;
return;
}
}
Is this what you are looking for?
If the User holds the MouseDown for 1 second, the evnt is fired?
public partial class Window2 : Window
{
private DispatcherTimer _DispatcherTimer = new DispatcherTimer();
public Window2()
{
InitializeComponent();
MouseDown += _MouseDown;
MouseUp += _MouseUp;
_DispatcherTimer.Interval = TimeSpan.FromSeconds(1.0);
_DispatcherTimer.Tick += _DispatcherTimer_Tick;
}
private void _DispatcherTimer_Tick(object sender, EventArgs e)
{
_DispatcherTimer.Stop();
Title = DateTime.Now.ToString();
}
private void _MouseUp(object sender, MouseButtonEventArgs e)
{
_DispatcherTimer.Stop();
}
private void _MouseDown(object sender, MouseButtonEventArgs e)
{
_DispatcherTimer.Start();
}
}

C# BackgroundWorker class

Currently im trying to update my progress bar if the background worker reports something, heres my code
Form1.cs
namespace YTD
{
public partial class Form1 : Form
{
private Main app;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
int n;
bool isNumeric = int.TryParse(numberBox.Text, out n);
if (!String.IsNullOrWhiteSpace(emailBox.Text) && !String.IsNullOrWhiteSpace(passBox.Text) && !String.IsNullOrWhiteSpace(numberBox.Text) && isNumeric)
{
this.app = new Main(emailBox.Text, passBox.Text, n, logBox, statusBar, backgroundWorker1);
this.app.startMule();
}
else
{
MessageBox.Show("Please fill out all the form fields", "MuleMaker error");
}
}
}
}
And my Main.cs
namespace YTD.classes
{
public class Main
{
private String email;
private String password;
private int number;
private RichTextBox logBox;
private ProgressBar statusBar;
private BackgroundWorker threadWorker;
public Main(String email, String password, int number, RichTextBox logBox, ProgressBar statusBar, BackgroundWorker threadWorker)
{
// Define some variables
this.email = email;
this.password = password;
this.number = number;
this.logBox = logBox;
this.statusBar = statusBar;
this.threadWorker = threadWorker;
}
public void startMule()
{
// Set progressbar 100% value
statusBar.Maximum = this.number;
if (!threadWorker.IsBusy)
{
threadWorker.RunWorkerAsync();
}
}
private void threadWorker_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 1; i <= 10; i++)
{
// Perform a time consuming operation and report progress.
MessageBox.Show("ye");
System.Threading.Thread.Sleep(500);
threadWorker.ReportProgress(i * 10);
}
}
private void threadWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
statusBar.Increment(1);
}
}
}
Currently I get no errors but the progress bar value is not beeing changed.
Without the background worker i can update my progress bar fine but not while doing an expensive action.
Your posted Code does not reveal, if you registered your functions to the BackgroundWorker Events.
Creating a new BackgrounWorker isn't enough.
Here is an example:
public Class Main
{
public Main( ... )
{
BackgroundWorker worker = new BackgroundWorker()
worker.WorkerReportsProgress = true;
// Register to BackgroundWorker-Events
worker.DoWork += threadWorker_DoWork;
worker.ProgressChanged += threadWorker_ProgressChanged;
}
}
in addition you should tell your ProgressBar to rerender.
private void threadWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
statusBar.Increment(1);
statusBar.Invalidate(true);
}
at least you might want to use the value you have set calling ReportProgress(i * 10).
private void threadWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
statusBar.Value = e.ProgressPercentage;
statusBar.Invalidate(true);
}

Threads with common variable

I'm building a NFS joystick manipulating the MouseWheel events. On my main thread I call a second thread that pulses keyboard keys with a generated frequency. My problem is that this frequency dynamically changes in time when you move up or down the MouseWheel but the simulator thread doesn't notice this change. This is a fragment of my code:
int centro = 0;
static bool left;
static bool ismoving;
static int grado;
static int frec;
Thread simulator = new Thread(new ThreadStart(move));
public Form1()
{
InitializeComponent();
}
static void mleft()
{
KeyboardSimulator.KeyDown(Keys.G);
Thread.Sleep(10);
KeyboardSimulator.KeyUp(Keys.G);
}
static void mright()
{
KeyboardSimulator.KeyDown(Keys.J);
Thread.Sleep(10);
KeyboardSimulator.KeyUp(Keys.J);
}
static void move()
{
while (ismoving)
{
if (left)
{
mleft();
Thread.Sleep(frec);
}
else
{
mright();
Thread.Sleep(frec);
}
}
}
void map()
{
if (grado == 0)
{
ismoving = false;
frec = 0;
}
else
{
int ut = 1000;//1seg
left = grado > 0;
grado = Math.Abs(grado);
frec = ut / grado / 10;
ismoving = true;
}
}
private void Window_Closed_1(object sender, EventArgs e)
{
simulator.Abort();
}
private void Form1_Load(object sender, EventArgs e)
{
HookManager.MouseWheel += Window_MouseWheel_1;
simulator = new Thread(new ThreadStart(move));
}
private void Window_MouseWheel_1(object sender, MouseEventArgs e)
{
centro += e.Delta;
grado = centro / 120;
l1.Text = grado + "";
map();
}

avoid click event while panel is refreshing

i have two panel in ma form. panel1 with button1 on it at location let say x:10,y:10 and panel2 with button 2 on it at location x:10,y:10.
what actually button1 do:- it hide panel1 and shows panel2 at the same location.
but whenever i click on button1 twice after completion its process it fire button2 click event,
plz help me ASAP
hope below link will demonstrate my prob clearly
http://www.youtube.com/watch?v=bpojl4XMweo&feature=g-upl
EDIT:
Code used so far
void hidepanel()
{
panel1.Visible = false;
panel2.Visible = false;
}
private void Form1_Load(object sender, EventArgs e)
{
hidepanel();
panel1.Visible = true;
panel2.Location = new Point(262,19);
panel1.Location = new Point(0, 0);
}
private void button1_Click(object sender, EventArgs e)
{
hidepanel();
panel2.Location = new Point(0, 0);
panel2.Visible = true;
}
private void button2_Click(object sender, EventArgs e)
{
MessageBox.Show("2");
}
just add some logic to hide/unhide enable/disable the oposite components. Just like this:
private void button1_Click(object sender, EventArgs e)
{
addLog("Button 1 clicked");
button1.Enabled = false;
button2.Enabled = false;
panel1.Visible = false;
panel2.Visible = true;
button2.Enabled = true;
}
private void button2_Click(object sender, EventArgs e)
{
addLog("Button 2 clicked");
button2.Enabled = false;
panel2.Visible = false;
panel1.Visible = true;
button1.Enabled = true;
}
works for me like a charme:
regards
Josef
EDIT:
Now, I see the problem, the mouse clicks are enqueued into windows message queue and will fire the click event on button2 although you clicked on a disabled/hidden button1.
I found the solution here: Ignoring queued mouse events
and changed the code to:
public static void ClearMouseClickQueue()
{
win32msg.NativeMessage message;
while (win32msg.PeekMessage(out message, IntPtr.Zero, (uint)win32msg.WM.WM_MOUSEFIRST, (uint)win32msg.WM.WM_MOUSELAST, 1))
{
}
}
...
private void button1_Click_1(object sender, EventArgs e)
{
addLog("Button 1 clicked");
button1.Enabled = false;
button2.Enabled = false;
panel1.Visible = false;
System.Threading.Thread.Sleep(2000);
ClearMouseClickQueue();
panel2.Visible = true;
button2.Enabled = true;
}
where PeekMessage etc is defined another class:
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace PanelTest
{
public static class win32msg
{
[DllImport("coredll.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool PeekMessage(out NativeMessage lpMsg, IntPtr hWnd, uint wMsgFilterMin, uint wMsgFilterMax, uint wRemoveMsg);
public enum WM : uint{
/// <summary>
/// Use WM_MOUSEFIRST to specify the first mouse message. Use the PeekMessage() Function.
/// </summary>
WM_MOUSEFIRST = 0x0200,
/// <summary>
/// Use WM_MOUSELAST to specify the last mouse message. Used with PeekMessage() Function.
/// </summary>
WM_MOUSELAST = 0x020E,
}
[StructLayout(LayoutKind.Sequential)]
public struct NativeMessage
{
public IntPtr handle;
public uint msg;
public IntPtr wParam;
public IntPtr lParam;
public uint time;
public System.Drawing.Point p;
}
}
}
Please test.
~josef

Categories

Resources