Fading in and fading out for a form - c#

i have a requirement in which my form is transparent,if my mouse enters into it the form
should became visible,if my mouse leaves out of the form it becomes transparent, i have three different controls placed in my form , each controls mouse leave and mouse enter is the same that of the form . if my mouse enters into the form and enters into a control
form_mouseleaveevent and control_mouseenterd gets fired so iam not able to achieve it,how to overcome this.
below is the piece of code for this:
private void TransToOpac()
{
if (!isTransparent)
return;
if (TtoOON == false )
{
TtoOON = true;
for (i = this.Opacity; i <= 1; i = i + 0.02)
{
this.Opacity = i;
Thread.Sleep(50);
}
isTransparent = false;
TtoOON = false;
}
}
private void OpacToTrans()
{
if (isTransparent)
return;
if (OtoTON == false )
{
OtoTON = true;
for (i = this.Opacity; i >= 0.5; i = i - 0.02)
{
this.Opacity = i;
Thread.Sleep(50);
}
isTransparent = true;
OtoTON = false;
}
}
private void OnMouseEntered(object sender, EventArgs e)
{
TransToOpac();
}
private void OnMouseLeft(object sender, EventArgs e)
{
OpacToTrans();
}

You can't get this done with MouseEnter/Leave events. The smaller problem is that the form's Leave event may never fire if a control is close to the edge. The bigger problem is that it will fire when the cursor moves into the non-client area (border, caption), you don't want to fade the form when the user tries to close or resize the window.
The crude but effective solution is to use a timer to check where the mouse is located:
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
this.Opacity = 0.99; // Avoid flicker
mFadeTimer.Interval = 15;
mFadeTimer.Tick += new EventHandler(mFadeTimer_Tick);
mMouseTimer.Interval = 200;
mMouseTimer.Tick += new EventHandler(mMouseTimer_Tick);
mMouseTimer.Enabled = true;
}
void mMouseTimer_Tick(object sender, EventArgs e) {
if (this.Bounds.Contains(Control.MousePosition)) {
if (mFade <= 0) { mFade = 1; mFadeTimer.Enabled = true; }
}
else {
if (mFade >= 0) { mFade = -1; mFadeTimer.Enabled = true; }
}
}
void mFadeTimer_Tick(object sender, EventArgs e) {
double opaq = this.Opacity + mFade * 0.05;
if (opaq >= 0.99) { opaq = 0.99; mFadeTimer.Enabled = false; }
if (opaq <= 0.15) { opaq = 0.15; mFadeTimer.Enabled = false; }
this.Opacity = opaq;
}
private Timer mFadeTimer = new Timer();
private Timer mMouseTimer = new Timer();
private int mFade = 0;
}

You could also check in Form_MouseLeave whether the mouse pointer is still within the form's bounds and in that case not fade out.
EDIT
There are several ways to find out whether the mouse is still within form's bounds. Easiest would be to use the Mouse.GetPosition method to find the current mouse position. The result is the location of the mouse pointer in screen coordinates. You can then check, whether the form's bounding rectangle contains the location.

Related

How to move a winforms tool to the right and then to the left continuously in the forms by using point class and timer tools?

Purpose of this code was to move a title(label) first rightwards until it hits the 600th pixel on the X axis and then leftwards until it hits the 27th pixel on the X axis of the form by using 2 timer tools and the Point class. One timer for going right and the other timer for going left. They should've work by swithing on and off consecutively after one another, however it does not work.
The label is stuck at 600th X location and does not move back to where it was.
The timer interval is 100 so it moves with a decent speed that allows us to see it moving.
namespace AlanCevreHesabiUygulamasi
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
if (label11Point.X == 27)
{
timer2.Stop();
timer1.Start();
}
if (label11Point.X == 599)
{
timer1.Stop();
timer2.Start();
}
}
Point label11Point = new Point(27, 32);
private void timer1_Tick(object sender, EventArgs e)
{
while (label11Point.X <= 600)
{
label12.Text = label11Point.X.ToString();
label11Point.X += 1;
label11.Location = label11Point;
break;
}
}
private void timer2_Tick(object sender, EventArgs e)
{
while (label11Point.X >= 27)
{
label12.Text = label11Point.X.ToString();
label11Point.X -= 1;
label11.Location = label11Point;
break;
}
}
}
}
Label is stuck at 600th pixel of the form, does not move back. How to make it work?
I'm surprised you see movement resulting from a while loop in a timer tick handler. Why have a timer if your are going to do it that way.
In this solution, I have a timer, and the movements happen during a timer tick. I also have three possible directions, Right, Left and Stopped (in case you want to have a start/stop button).
In the Windows Forms designer, I dropped both a label and a timer on the form. I left their properties alone except for the timer's Interval property (that I set to 10 (ms))
Then I added an enum and an instance of the enum as a field to the Form class:
public partial class Form1 : Form
{
private enum Direction { MoveRight, MoveLeft, Stopped }
Direction _direction;
public Form1()
{
InitializeComponent();
}
}
I double-clicked the Caption area of the form in the designer to create a form Load handler, and added a call to start the timer:
private void Form1_Load(object sender, EventArgs e)
{
timer1.Start();
}
Finally, I double-clicked the timer to get a timer Tick handler and added some code:
private void timer1_Tick(object sender, EventArgs e)
{
var curLocation = label1.Location;
if (_direction == Direction.MoveRight && curLocation.X > 600)
{
_direction = Direction.MoveLeft;
}
else if (_direction == Direction.MoveLeft && curLocation.X < 27)
{
_direction = Direction.MoveRight;
}
int offset = _direction switch
{
Direction.MoveRight => 1,
Direction.MoveLeft => -1,
_ => 0,
};
curLocation.X += offset;
label1.Location = curLocation;
}
The _direction field determines if the label is moving to the right or the left.
How can you write the code without a timer?"
You asked "How can you write the code without a timer?" I'm still flabbergasted that your label moves as the result of a while loop in an event handler - something must have changed from my good-old understanding of Win32 processing.
Anyways, I cheat and await a call to Task.Delay instead of using a timer. Take my existing code and do the following:
Add two buttons to your form (One labeled Start (named StartBtn) and the other labeled Stop (named StopBtn).
Add another Direction-typed field to the class: Direction _previousDirection;
Comment out the call to timer1.Start(); in the Form1_Load handler
Comment out all the code in the timer1_Tick method (at this point, you could remove the timer from the form if you want)
Select both buttons (Start and Stop) and press <Enter>. This will bring up click handlers for both buttons.
Change the StopBtn button's handler to look like:
New Stop Button code:
private void StopBtn_Click(object sender, EventArgs e)
{
_previousDirection = _direction;
_direction = Direction.Stopped;
}
Change the StartBtn's handler to look like the following. Note that nearly everything in the while loop (except the call to Task.Delay) is the same as the previous timer tick handler code. Also note that I made the handler async void to allow for the await keyword to do it's magic.
Start Button code:
private async void StartBtn_Click(object sender, EventArgs e)
{
_direction = _previousDirection;
while (_direction != Direction.Stopped)
{
var curLocation = label1.Location;
if (_direction == Direction.MoveRight && curLocation.X > 600)
{
_direction = Direction.MoveLeft;
}
else if (_direction == Direction.MoveLeft && curLocation.X < 27)
{
_direction = Direction.MoveRight;
}
int offset = _direction switch
{
Direction.MoveRight => 1,
Direction.MoveLeft => -1,
_ => 0,
};
curLocation.X += offset;
label1.Location = curLocation;
await Task.Delay(10);
}
}
I solved it, I don't know why but in my opening post the Form1() function only makes one of the if() conditions work. However, putting the if() statements into the timers solved the problem. Now, the title goes back and forth in the specified x axis intervals.
namespace AlanCevreHesabiUygulamasi
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
timer1.Start();
}
Point label11Point = new Point(27, 32);
private void timer1_Tick(object sender, EventArgs e)
{
while (label11Point.X >= 27)
{
label12.Text = label11Point.X.ToString();
label11Point.X += 1;
label11.Location = label11Point;
break;
}
if (label11Point.X == 600)
{
timer2.Start();
timer1.Stop();
}
}
private void timer2_Tick(object sender, EventArgs e)
{
while (label11Point.X <= 600)
{
label12.Text = label11Point.X.ToString();
label11Point.X -= 1;
label11.Location = label11Point;
break;
}
if (label11Point.X == 27)
{
timer1.Start();
timer2.Stop();
}
}

Button.Enabled not working on first of several buttons in BackgroundWorker

I have several buttons that I want turned off/on at different times. I put these into a function for simplicity. Enabling the buttons is called by a BackgroundWorker so that I can update a camera view at the same time as listening to a Serial port for an 'enable' signal. Disabling the controls is called by the button click, while enable is handled by the BackgroundWorker (it watches for the Serial port signal). All buttons re-enable, except for the first one listed in enableControls();. If I change the order of enableControls() then the button at top is left disabled. What is causing this? I would think that either all buttons or no buttons would be re-enabled.
private void btnLeft_Click(object sender, EventArgs e) // All buttons are similar, just different output to port
{
disableControls();
hardWorker.RunWorkerAsync();
int stepSize = Convert.ToInt32(ddStepSize.Text);
string outString;
if (moveSampHome == false)
{
outString = "#MOVER" + stepSize;
posX = posX - RcDrawSlide.Width * stepSize / (1000 * Convert.ToInt32(slideSizeX));
}
else { outString = "#MSMPR" + stepSize; }
port.Write(outString + "\n");
}
private void hardWorker_DoWork(object sender2, DoWorkEventArgs f)
{
arduinoIn = "0";
for (int i = 0; i == 0;)
{
if (arduinoIn != null)
{
if (arduinoIn.Contains("1"))
{
i = 1;
arduinoIn = "0";
}
}
}
port.Write("1");
}
private void hardWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
enableControls();
}
private void enableControls()
{
btnBack.Enabled = true; // Swap this for any other button - that one will not be enabled.
btnForward.Enabled = true;
btnLeft.Enabled = true;
btnRight.Enabled = true;
}
private void disableControls()
{
btnBack.Enabled = false;
btnForward.Enabled = false;
btnLeft.Enabled = false;
btnRight.Enabled = false;
}
If I add a button that runs enableControls() on click everything is reenabled, so I know this is due to having it run from a BackgroundWorker. I think that BackgroundWorker is necessary, though. I'm just unsure why it's only the first btn.Enabled = true; that doesn't work. Is there a workaround for this?
For hardWorker_DoWork() try something more like:
private void hardWorker_DoWork(object sender2, DoWorkEventArgs f)
{
arduinoIn = "0";
while (arduino == null || !arduinoIn.Contains("1")) {
System.Threading.Thread.Sleep(0); // or try a SMALL number like 50!
}
arduinoIn = "0";
port.Write("1");
}
Is it possible the buttons are being enabled again when data is received on the port? You haven't shown any code relating to that side...

I have a glitch in my program which keeps opening a specific form over and over again after the form is hidden

I am an AS Software Development student and I have made an Electronics Quiz for my CA. I have come across a glitch which I cannot seem to fix. It has started to bug me and I can't think of what is wrong. My teacher also cannot see what is wrong. Everything else is working. Here is the code:
namespace MyQuiz2
{
public partial class DragDropYear8_Question1 : Form
{
public DragDropYear8_Question1(string name, int quizSelection)
{
InitializeComponent();
CenterToScreen();
setupQuestion();
}
private void setupQuestion()
{
AllowDropping();
ScoreLbl.Text = "Score: " + StartScreen.Player.Score;
LEDImg.Visible = true;
ResistorImg.Visible = true;
VairiableResistorImg.Visible = true;
timer1.Interval = 1000;
timer1.Start();
if (_time1 == 0)
{
ShowNextQuestion();
}
}
//variable decleration
private int _time1 = 15;
private int _correctAnswers = 0;
//Set up timer
private void timer1_Tick(object sender, EventArgs e)
{
_time1--;
TimerLbl.Text = "Time: " + _time1;
}
//Question setup
private void ShowNextQuestion()
{
_time1 = 0;
Hide();
new DragDropYear8_Question2(StartScreen.Player.Username, 10).Show();
}
private void AllowDropping()//allows the label to be dropped onto a picture box.
{
VairiableResistorImg.AllowDrop = true;
ResistorImg.AllowDrop = true;
LEDImg.AllowDrop = true;
}
//Tells the program that a label has been grabbed
private void LabelGrabbed(object sender, MouseEventArgs e)
{
Label selectedLabel = (Label)sender;
selectedLabel.DoDragDrop(selectedLabel.Text, DragDropEffects.Copy);
}
//allows the label to be droped onto the PictureBox
private void AllowDragDropCopy(object sender, DragEventArgs e)
{
e.Effect = DragDropEffects.Copy;
}
private void UpdateScoreAndLabelWhenCorrect()//updates all labels on the current form if the answers are correct
{
_correctAnswers++;
StartScreen.Player.IncreaseScore();
ScoreLbl.Text = "Score: " + StartScreen.Player.Score;
if (_correctAnswers == 3)
{
ShowNextQuestion();
}
}
private void UpdateScoreAndLabelWhenWrong()//updates all labels on the current form if the answers are incorrect
{
_correctAnswers++;
ScoreLbl.Text = "Score: " + StartScreen.Player.Score;
if (_correctAnswers == 3)
{
ShowNextQuestion();
}
}
//checks if the right label has been dropped onto the correct picture box
private void VairiableResistorDragDrop(object sender, DragEventArgs e)
{
string result = (string)e.Data.GetData(DataFormats.Text);
/*if the correct label is droped then the score and labels
will be updated and that label and picture box will hide*/
if (result == "Vairiable Resistor")//checks for right answer
{
UpdateScoreAndLabelWhenCorrect();
VairiableResistorImg.Visible = false;
VairiableResistorLbl.Visible = false;
}
//if the anser is wrong then it will hide the picture box and the dragged label
else if (result == "Resistor")
{
UpdateScoreAndLabelWhenWrong();
ResistorLbl.Visible = false;
VairiableResistorImg.Visible = false;
}
else if (result == "Light Emmiting Diode")
{
UpdateScoreAndLabelWhenWrong();
LEDLbl.Visible = false;
VairiableResistorImg.Visible = false;
}
}
private void LEDDragDrop(object sender, DragEventArgs e)
{
string result = (string)e.Data.GetData(DataFormats.Text);
/*if the correct label is droped then the score and labels
will be updated and that label and picture box will hide*/
if (result == "Light Emmiting Diode")//checks for right answer
{
UpdateScoreAndLabelWhenCorrect();
LEDImg.Visible = false;
LEDLbl.Visible = false;
}
//if the anser is wrong then it will hide the picture box and the dragged label
else if (result == "Resistor")
{
UpdateScoreAndLabelWhenWrong();
ResistorLbl.Visible = false;
LEDImg.Visible = false;
}
else if (result == "Vairiable Resistor")
{
UpdateScoreAndLabelWhenWrong();
LEDImg.Visible = false;
VairiableResistorLbl.Visible = false;
}
}
private void ResistorDragDrop(object sender, DragEventArgs e)
{
string result = (string)e.Data.GetData(DataFormats.Text);
/*if the correct label is droped then the score and labels
will be updated and that label and picture box will hide*/
if (result == "Resistor")//checks for right answer
{
UpdateScoreAndLabelWhenCorrect();
ResistorImg.Visible = false;
ResistorLbl.Visible = false;
}
//if the anser is wrong then it will hide the picture box and the dragged label
else if (result == "Light Emmiting Diode")
{
UpdateScoreAndLabelWhenWrong();
ResistorImg.Visible = false;
LEDLbl.Visible = false;
}
else if (result == "Vairiable Resistor")
{
UpdateScoreAndLabelWhenWrong();
ResistorImg.Visible = false;
VairiableResistorLbl.Visible = false;
}
}
}`
The problem is that when I change from the first dragdrop question to the second dragdrop question. Randomly during the second form, the first dragdrop question form will open. It does this the hole way through the quiz. Latter on in the quiz the game loadscreen also does this. The code is as follows:
namespace MyQuiz2
{
public partial class GameLoading : Form
{
public GameLoading()
{
InitializeComponent();
CenterToScreen();
timer1.Start();
}
//Timer and Progressbar setup
private void timer1_Tick(object sender, EventArgs e)
{
//randome number generator for ProgressBar increments
Random random = new Random();
int Increment = random.Next(10, 20);
Random random2 = new Random();
int _Increment = random2.Next(1, 5);
timer1.Interval = 1000;
if (progressBar1.Value <= 80)
{
progressBar1.Increment(Increment);
/*picks a random number between 5 and 10 to increment the ProgressBar by if
the value of the Progress bar is less than or equal to 80*/
}
else
{
progressBar1.Increment(_Increment);
// picks a randome number between 1 and 5 to incremnt by when the ProgressBar is more then 80
}
LoadingLbl.Text = "Loading Game..." + progressBar1.Value + "%";
//When progress bar is at its maximum value the next form will show
if (progressBar1.Value == progressBar1.Maximum)
{
timer1.Stop();
LoadingLbl.Text = "Loading Game... 100%";
CheckScore();
}
}
private void CheckScore()
{
if (StartScreen.Player.Score >= 20)
{
MessageBox.Show("Congratulations, you got more than 80% of the quiz correct. You can proceed to the Game", "Well done!!");
timer1.Stop();
new GameMenu().Show();
Hide();
}
else
{
MessageBox.Show("You got under 80% in the quiz but you can't play the game. Try again.", "Unlucky, Try again");
timer1.Stop();
new EndScreen(false).Show();
Hide();
}
}
}
}
I have
I will link if you would like to have a look for yourself(the source code and a video is included). Thanks
This screen shot shows the problem at the drag drop questions. As you an see from this image, it keeps on multiplying. The same thing happens with the game loading screen
I think the problem is that the timer does not stop which will keep on opening the forms but I'm not sure. I hope this lets you understand my problem better. Thanks
You an still call each question as a form. I would have a function that shows the requested question. This can be called by a second function that can keep track of the question you are on. Also, I would probably call and destroy each form, so that you don't have unnecessary forms hanging around. Something like this (writing this on my phone so take it as an outline more than direct code) :
public void CallQuestions()
{
int QuestionNumber = 1;
do {
if Question(QuestionNumber)
QuestionNumber++;
} while (Exit == false) ;
}
public boolean Question(int number)
{
Form QuestionForm = null;
switch (number)
{
case 1:
QuestionForm = new DragDropYear8_Question1;
break;
//...
}
if (QuestionForm.ShowDialog() == DialogResult.Ok)
return true;
return false;
}

c# - disable events during MouseDoubleClick

Is it possible to disable other MouseEvent during a MouseDoubleClick event?
I've registered multiple events on a label but i want MouseDoubleClick is prioritary and block all other MouseEvent (es. MouseDown or MuoseMove). Then, after the DoubleClickHandler is finished i want to reactivate them.
You can create a flag to store your different states in order for your methods to know what they have to know.
A simple approach will be something like:
bool dblClickDone = false;
void DoubleClickHandler(...)
{
//...
dblClickDone = true;
}
void MouseDownHandler(...)
{
if (dblClickDone) {
//...
}
}
You get the idea.
Just unregister the events using "-=", example:
private void OnMouseDoubleClick(object sender, MouseEventArgs e)
{
this.MouseDown -= MethodOnMouseDown;
this.MouseMove -= MethodOnMouseMove;
// Do something.....
this.MouseDown += MethodOnMouseDown;
this.MouseMove += MethodOnMouseMove;
}
MSDN suggests two methods. The one you use will be based on the design of you program. I've copied the code from MSDN below in case the page goes down.
First method is to rollback any changes made that were made in the 'single click' event if the double click event is fired.
using System;
using System.ComponentModel;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace MouseRollBackSingleClick
{
public class Form1 : Form
{
private DoubleClickButton button1;
private FormBorderStyle initialStyle;
public Form1()
{
initialStyle = this.FormBorderStyle;
this.ClientSize = new System.Drawing.Size(292, 266);
button1 = new DoubleClickButton();
button1.Location = new Point (40,40);
button1.Click += new EventHandler(button1_Click);
button1.AutoSize = true;
this.AllowDrop = true;
button1.Text = "Click or Double Click";
button1.DoubleClick += new EventHandler(button1_DoubleClick);
this.Controls.Add(button1);
}
// Handle the double click event.
void button1_DoubleClick(object sender, EventArgs e)
{
// Change the border style back to the initial style.
this.FormBorderStyle = initialStyle;
MessageBox.Show("Rolled back single click change.");
}
// Handle the click event.
void button1_Click(object sender, EventArgs e)
{
this.FormBorderStyle = FormBorderStyle.FixedToolWindow;
}
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.Run(new Form1());
}
}
public class DoubleClickButton : Button
{
public DoubleClickButton() : base()
{
// Set the style so a double click event occurs.
SetStyle(ControlStyles.StandardClick |
ControlStyles.StandardDoubleClick, true);
}
}
}
The second method is to create a timer which triggers when the single click is performed. If a double click is not followed within the timer limit, it's assumed the user wants to perform a single click and that action is taken, otherwise the double click action is taken.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace SingleVersusDoubleClick
{
class Form1 : Form
{
private Rectangle hitTestRectangle = new Rectangle();
private Rectangle doubleClickRectangle = new Rectangle();
private TextBox textBox1 = new TextBox();
private Timer doubleClickTimer = new Timer();
private ProgressBar doubleClickBar = new ProgressBar();
private Label label1 = new Label();
private Label label2 = new Label();
private bool isFirstClick = true;
private bool isDoubleClick = false;
private int milliseconds = 0;
[STAThread]
public static void Main()
{
Application.EnableVisualStyles();
Application.Run(new Form1());
}
public Form1()
{
label1.Location = new Point(30, 5);
label1.Size = new Size(100, 15);
label1.Text = "Hit test rectangle:";
label2.Location = new Point(30, 70);
label2.Size = new Size(100, 15);
label2.Text = "Double click timer:";
hitTestRectangle.Location = new Point(30, 20);
hitTestRectangle.Size = new Size(100, 40);
doubleClickTimer.Interval = 100;
doubleClickTimer.Tick +=
new EventHandler(doubleClickTimer_Tick);
doubleClickBar.Location = new Point(30, 85);
doubleClickBar.Minimum = 0;
doubleClickBar.Maximum = SystemInformation.DoubleClickTime;
textBox1.Location = new Point(30, 120);
textBox1.Size = new Size(200, 100);
textBox1.AutoSize = false;
textBox1.Multiline = true;
this.Paint += new PaintEventHandler(Form1_Paint);
this.MouseDown += new MouseEventHandler(Form1_MouseDown);
this.Controls.AddRange(new Control[] { doubleClickBar, textBox1,
label1, label2 });
}
// Detect a valid single click or double click.
void Form1_MouseDown(object sender, MouseEventArgs e)
{
// Verify that the mouse click is in the main hit
// test rectangle.
if (!hitTestRectangle.Contains(e.Location))
{
return;
}
// This is the first mouse click.
if (isFirstClick)
{
isFirstClick = false;
// Determine the location and size of the double click
// rectangle area to draw around the cursor point.
doubleClickRectangle = new Rectangle(
e.X - (SystemInformation.DoubleClickSize.Width / 2),
e.Y - (SystemInformation.DoubleClickSize.Height / 2),
SystemInformation.DoubleClickSize.Width,
SystemInformation.DoubleClickSize.Height);
Invalidate();
// Start the double click timer.
doubleClickTimer.Start();
}
// This is the second mouse click.
else
{
// Verify that the mouse click is within the double click
// rectangle and is within the system-defined double
// click period.
if (doubleClickRectangle.Contains(e.Location) &&
milliseconds < SystemInformation.DoubleClickTime)
{
isDoubleClick = true;
}
}
}
void doubleClickTimer_Tick(object sender, EventArgs e)
{
milliseconds += 100;
doubleClickBar.Increment(100);
// The timer has reached the double click time limit.
if (milliseconds >= SystemInformation.DoubleClickTime)
{
doubleClickTimer.Stop();
if (isDoubleClick)
{
textBox1.AppendText("Perform double click action");
textBox1.AppendText(Environment.NewLine);
}
else
{
textBox1.AppendText("Perform single click action");
textBox1.AppendText(Environment.NewLine);
}
// Allow the MouseDown event handler to process clicks again.
isFirstClick = true;
isDoubleClick = false;
milliseconds = 0;
doubleClickBar.Value = 0;
}
}
// Paint the hit test and double click rectangles.
void Form1_Paint(object sender, PaintEventArgs e)
{
// Draw the border of the main hit test rectangle.
e.Graphics.DrawRectangle(Pens.Black, hitTestRectangle);
// Fill in the double click rectangle.
e.Graphics.FillRectangle(Brushes.Blue, doubleClickRectangle);
}
}
}
I've had similar problem with having events on double click and mouse up. I've experienced that the mouse up during the double click gets triggered twice during a double click as is reasonable.
What worked best for me was to hide the mouse up behind two levels on when it can be triggered. A bool and a timer with an interval short enough not to be noticeable by the user but longer than the interval between clicks in a double click.
The bool let's call it canMouseUp is true by default. and should be set to false during a double click to ignore the mouse up as the double click is finished.
the mouse up checks for canMouseUp and if it is false then it is set to true, nothing else. If canMouseUp is true then I start the mouseUpTimer.
double click stops the mouseUpTimer, sets canMouseUp to false and does it's own thing.
private void MyObject_MouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
try
{
if (!canMouseUp)
{
canMouseUp= true;
e.Handled = true;
}
else
{
mouseUpTimer.Start();
e.Handled = true;
}
}
catch (Exception)
{
throw;
}
}
private void MyObject_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
try
{
mouseUpTimer.Stop();
// Do what DoubleClick is supposed to do
canMouseUp = false;
e.Handled = true;
}
catch (Exception)
{
throw;
}
}
private void mouseUpTimer_Elapsed(object sender, ElapsedEventArgs e)
{
try
{
// Do what Mouse up is supposed to do.
}
catch (Exception)
{
}
}

C# Clickable And Transparent Form

I'm trying to do transparent and clickable form. This form will work full screen. So this form must be clickable. For example if desktop exists behind this form, I must be able to click to folders and open.
If a document exists I must be able to change this document. I couldn't solve how to enable this.
I think it can be done with API codes, but I don't know which API. If you can give me some information/link I will be pleased.
This is simple and works without calling any API function.
But it will prohibit any interaction of your program with the user..
For a Screensaver this makes no sense, however, at least not as you described it.
The rule is this:
Anything that is not 100% transparent is not click-through.
So you could easily create a darker screen using Opacity and a Black BackColor but it won't be click-through.
The simplest solution would be to switch between the both modes upon MouseMove using a Timer to turn the saving mode back on, maybe like this:
public Form1()
{
InitializeComponent();
this.Text = "";
this.MinimizeBox = false;
this.MaximizeBox = false;
this.ControlBox = false;
this.WindowState = FormWindowState.Maximized;
switchSaverState(false);
}
Point lastMosePosition = Point.Empty;
int savingWaitMinutes = 10;
int minute = 60000;
Timer timer1 = new Timer;
void switchSaverState(bool saving)
{
if (saving)
{
this.BackColor = Color.Black;
this.Opacity = 0.8;
}
else
{
this.TransparencyKey = Color.Fuchsia;
this.BackColor = Color.Fuchsia;
this.Opacity = 1;
timer1.Interval = minute * savingWaitMinutes;
timer1.Start();
}
}
private void timer1_Tick(object sender, EventArgs e)
{
if (timer1.Interval == minute * savingWaitMinutes)
{
timer1.Interval = 100;
switchSaverState(true);
lastMosePosition = Cursor.Position;
}
else
{
if (Cursor.Position != lastMosePosition) { switchSaverState(false); }
}
}
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
lastMosePosition = Cursor.Position;
switchSaverState(false);
}
But again: This is like a Screensver, meaning that you can't work while it 'saves'! To do that use the controls on your monitor!!

Categories