C# Monogame - detect mouse hold - c#

I'm writing a complex GUI for my game's main menu. I have already created a ButtonGUI class with it's own constructor with the parameters of button text, text color etc. I have a background texture drawn behind the text for every button, to make it look pretty. So I implemented a simple mouse input system:
void DetectBtnInput(ButtonGUI btn)
{
if (mouseRect.Intersects(btn.SourceRect))
{
btn.IsHovered = true;
if (mouseState.LeftButton == ButtonState.Pressed) settingsWindow.isOpen = true;
}
}
This method is called in Update(GameTime gameTime) for each instance of the ButtonGUI class. So mouseRect = new Rectangle(mouseState.X, mouseState.Y, 1, 1);
each instance of the ButtonGUI class has a Rectangle SourceRect property, which is equal to the position of the button passed to the constructor (obviously the button's size is the same every time). The logic behind the above code is simple, if the mouse is hovering the button instance's SourceRect, btn.IsHovered is set to true, it changes text color. When clicked, my WindowGUI class instance opens with additional settings.
So my aim is at making these buttons look nice and have the Windows styled button mechanics. So I am looking for a code to check for mouse hold-like event and have for example a bool that changes the button texture or whatever I can do myself. But the problem is that I tried incorporating the solution people give about the previousMouseState and the newMouseState, but I am not certain as if it works in Monogame as it worked in XNA... Or was my implementation wrong? Can I have a clearer example on how you handle mouse-hold in your games? Thanks in advance!

If you mean the player can click and hold (as per question title), and nothing happens until they then release. previous and current state should work fine as an implementation such as.
Forgive any incorrections in syntax, hopefully you can take this as pseudo code enough to make your own.
MouseState prev, curr;
curr = GetMouseState();
update()
{
prev = curr;
curr = GetMouseState();
// Simple check for a mouse click (from being held down)
if (curr == MouseState.Up && prev == MouseState.Down)
{
// Do mouse stuff here
}
}

Related

C# Monogame - handling mouse

I'm trying to understand what is the proper way of handling mouse input when there are multiple objects on the screen that can be clicked. I have a custom Mouse class and many "game objects" on the screen that can be clicked (say like buttons of a gui). In many simple tutorials I see people check for mouse-pressed or released inside the Update method of each game object instance present on the scene and then the particular clicked object invokes an event that it has been clicked. But having say 20 or 30 or more of these objects - each with a different function means that the "top layer" (the manager of these objects) has to subscribe to all the OnClick events of all the buttons and call the respective function. Is this the correct way? (I'm not asking for an opinion - I know that each can program it's own way) Is there a less cumbersome way of programming this?
The "solution" that I was thinking is putting the click event ivocation in the Mouse class. So the mouse will notify the game/state/ui-manager that a click occured, passing the mouse coordinates and buttin clicked in the eventArgs. Then (and not at each game loop as before) the "manager" would find the game-object that has been clicked over. This might work for click events but is it possible to implement the mouse hover functionality in this way too?
Thanks for your 2 cents.
I prefer to implement a static InputManager class to provide a common input across platforms and input devices.
Here are snippets of that class relevant to your question:
public static class InputManager
{
public static bool LeftClicked = false;
private static MouseState ms = new MouseState(), oms;
public static void Update()
{
oms = ms;
ms = Mouse.GetState();
LeftClicked = ms.LeftButton != ButtonState.Pressed && oms.LeftButton == ButtonState.Pressed;
// true On left release like Windows buttons
}
public static bool Hover(Rectangle r)
{
return r.Contains(new Vector2(ms.X,ms.Y));
}
}
The first line of Update in game1.cs:
InputManager.Update();
In any of your game objects' Update method with a collision or draw rectangle named rect:
if (InputManager.Hover(rect))
{
// do hover code here
if(InputManager.LeftClicked)
{
//Do click action here
}
}
else
{
//undo hover code here
}
The only time I used a native input event callback with MonoGame was in an Android App to register/process swipes that could occur faster than 16.66ms, 60 fps.(There were no Threading issues involved in that case)

Lag when frequently moving and redrawing a control

Moving Label inside parent's MouseMove-events causes trailing redraw.
I am (mis)using System.Windows.Forms.Label objects to realize
A more flexible tooltip,
Displaying a cross hair "cursor" extending to the borders of a parent control.
To that end I create the labels as members of the parent control (btw. it's a custom graphics control with mouse wheel zoom, panning etc.), add them to the parent's Controls-list, and move them inside the MouseMove-event of the parent. In order to ensure crisp movement behavior, I even call Label.Refresh when assigning the Location property of the Labels.
void GraphViewMouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
{
if (lastLocation != e.Location)
{
HasMoved = true;
if (IsPanning && e.Button == MouseButtons.Left)
{
if (isSelecting) PerformSelection(e.Location);
else PerformMove(e.Location,lastLocation);
}
lastLocation = e.Location;
if (Width > 0 && Height > 0)
{
PointD pos = CursorPosition;
// nothing interesting, basically like what is done with the crossHair's below
coordinateToolTip.Locate(lastLocation, pos.X, pos.Y);
crossHairX.Location = new Point(lastLocation.X, 0);
crossHairY.Location = new Point(0, lastLocation.Y);
crossHairX.Refresh();
crossHairY.Refresh();
}
}
}
Everything works almost fine (the labels move parallel to the mouse cursor) except that when I move the mouse a little faster, several copies of the Label(s) remain in the client area of the parent for some time like a visual echo.
That is, whereas the redraw of the labels at their new location appears to occur immediately, it seems to take some fraction of a second until the background of the parent (some complicated graphics, the complete redraw of which takes several seconds, but is definitely not redrawn during said simple mouse move) is restored to what has been behind the moving Label(s) originally. This is of course functionally irrelevant, but it simply looks ugly because it raises the impression that the code is inefficient.
Is there a way to enforce (faster) redraw of the cached background graphics? What determines the delay before the screen content behind a control is restored?
Edit: as to the suggestion of setting DoubleBuffered=true: according to MSDN this should already be true by default. Indeed it doesn't make a difference if I set it true for the Label. On the other hand, setting it false introduces additional flickering as expected. In either case the restoration of the background remains delayed, like described above.
#Hans Passant: Thanks for telling us "When you move a control, its parent's OnPaintBackground() method needs to run to over-draw the pixels that were left behind by the control in its previous position."
For me the cp.ExStyle |= 0x02000000; // Turn on WS_EX_COMPOSITED did not work.
I am creating movable, Resizable Panel and when I moved it fast from left to right it was not displayed right "the half of the panel was often gone". I did this and now it works exactly like when I move a Windows Window.
This is in the MyPanel Class which I made and Inherits from Panel
protected override void OnMove(EventArgs e)
{
this.Parent.Invalidate();
base.OnMove(e);
}
So when I move the Movable panel with the mouse it wil Invalidate the "Parrent" in my case the Form and now it moves fine.

KinectRegion HandPointer Cursor as mouse cursor in Awesomium Browser

I would like to use the kinect hand cursor as 'normal' mouse cursor. In the specific I want to be able to interact with the Awesomium browser object.
The problem is that no Awesomium Browser event is raised when the kinect hand cursor is (for example) over a link, or I do a click, or any other typical mouse event.
I modified the Control Basics-WPF example program that you can find in the example directory of the Kinect SDK
I am using c# visual studio 2012, Kinect SDK 1.7, Awesomium 1.7.1.
It's been a month since this question's been asked, so perhaps you've already found your own solution.
In any case, I found myself in this scenario as well, and here was my solution:
Inside MainWindow.xaml, you'll need the Awesomium control inside a KinectRegion (from the SDK).
You'll have to somehow tell the SDK that you want a control to also handle hand events. You can do this by adding this inside MainWindow.xaml.cs on the Window_Loaded handler:
KinectRegion.AddHandPointerMoveHandler(webControl1, OnHandleHandMove);
KinectRegion.AddHandPointerLeaveHandler(webControl1, OnHandleHandLeave);
Elsewhere in MainWindow.xaml.cs, you can define the hand handler events. Incidentally, I did it like this:
private void OnHandleHandLeave(object source, HandPointerEventArgs args)
{
// This just moves the cursor to the top left corner of the screen.
// You can handle it differently, but this is just one way.
System.Drawing.Point mousePt = new System.Drawing.Point(0, 0);
System.Windows.Forms.Cursor.Position = mousePt;
}
private void OnHandleHandMove(object source, HandPointerEventArgs args)
{
// The meat of the hand handle method.
HandPointer ptr = args.HandPointer;
Point newPoint = kinectRegion.PointToScreen(ptr.GetPosition(kinectRegion));
clickIfHandIsStable(newPoint); // basically handle a click, not showing code here
changeMouseCursorPosition(newPoint); // this is where you make the hand and mouse positions the same!
}
private void changeMouseCursorPosition(Point newPoint)
{
cursorPoint = newPoint;
System.Drawing.Point mousePt = new System.Drawing.Point((int)cursorPoint.X, (int)cursorPoint.Y);
System.Windows.Forms.Cursor.Position = mousePt;
}
For me, the tricky parts were:
1. Diving into the SDK and figuring out which handlers to add. Documentation wasn't terribly helpful on this.
2. Mapping the mouse cursor to the kinect hand. As you can see, it involves dealing with System.Drawing.Point (separate from another library's Point) and System.Windows.Forms.Cursor (separate from another library's Cursor).

Prevent mouse from leaving my form

I've attached some MouseMove and MouseClick events to my program and next up is one of these:
Get "global" mouse movement, so that I can read the mouse location even outside the form.
Prevent my mouse from leaving the form in the first place.
My project is a game so it'd be awesome to prevent the mouse leaving my form like most other games do (ofc. you can move it out if you switch focus with alt+tab fe.) and taking a look at answers to other questions asking for global mosue movement, they seem pretty messy for my needs.
Is there an easy way to prevent my mouse from going outside my form's borders? Or actually to prevent it from going OVER the borders in the first place, I want the mouse to stay inside the client area.
Additional info about the game:
The game is a short, 5-30 seconds long survival game (it gets too hard after 30 seconds for you to stay alive) where you have to dodge bullets with your mouse. It's really annoying when you move your mouse out of the form and then the player (System.Windows.Forms.Panel attached to mouse) stops moving and instantly gets hit by a bullet. This is why preventing mouse from leaving the area would be good.
Late answer but might come in handy. You could subscribe the form to MouseLeave and MouseMove events and handle them like this :
private int X = 0;
private int Y = 0;
private void Form1_MouseLeave(object sender, EventArgs e)
{
Cursor.Position = new Point(X, Y);
}
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
if (Cursor.Position.X < this.Bounds.X + 50 )
X = Cursor.Position.X + 20;
else
X = Cursor.Position.X - 20;
if (Cursor.Position.Y < this.Bounds.Y + 50)
Y = Cursor.Position.Y + 20;
else
Y = Cursor.Position.Y - 20;
}
The above will make sure the mouse cursor never leaves the bounds of the form. Make sure you unsubscribe the events when the game is finished.
Edit :
Hans Passants's answer makes more sense than my answer. Use Cursor.Clip on MouseEnter :
private void Form1_MouseEnter(object sender, EventArgs e)
{
Cursor.Clip = this.Bounds;
}
You could free the cursor in case of any error/crash (I'm sure you could catch'em) :
Cursor.Clip = Rectangle.Empty;
You cannot trap the mouse, that would prevent the user from, say, operating the Start menu. Closest you can get is assigning the Cursor.Clip property. But it is easily defeated by the user pressing Ctrl+Esc for example, there is no notification for this.
Best thing to do is to subscribe the form's Deactivated event, it reliably tells you that the user switched to another program. The Activated event tells you when the user moved back. Of course the user will have few reasons to actually do this when the game score depends on keeping a game object moving. So don't forget to give the user an easy way to pause the game with, say, the Escape key.
I don't know a solution for your exact problem, but I have a completely different idea for you. I don't know how your game works, but based on what you told me, why not make it a step harder: Add borders to the game-area, for example 4 pixels wide rectangles, which you are not allowed to touch. If you touch them, you die and the mouse gets released.
You can use the Cursor class. For example:
int X = Cursor.Position.X;
int Y = Cursor.Position.Y;
As for preventing the user to move the mouse outside the form, the best approach would probably be if you had someway to know what is the coordinates of your form on the screen and attach a MouseMove event, and check if the mouse is inside the form rectangle.
To know the form position on the screen take a look at this question.
I wouldn't recommend the global mouse movement control for two reasons.
It's bad design, you should respect the bounds of the operating system. Make the application full screen if you want this kind of behaviour. The only applications that should perform these kind of operations are "kiosk" mode applications which lock down the entire OS (to prevent operator abuse).
Global key hooks are messy, aren't guaranteed to work and are dangerous because they affect a key part of the operating system (all controls). A bug in your code could result in requiring a reboot on the machine.
That said, last time I checked (a while ago, on Vista) SetWindowsHookEx still works (but its not officially supported IIRC), it's an unmanaged call so you'll have to pinvoke but with it you can refuse to pass on messages that would move the mouse outside of the bounds of your application. I'm not 100% sure if the OS will let you beat it to the cursor control (I've only blocked keyboards before on desktop boxes) but its probably your best shot.

tooltip on disabled control

happy holidays!
i have a tablelayoutpanel (10x10). within each cell i have a picturebox which are disabled (enabled = false).
i am trapping mouse move over the table to catch mouse movement. here is the code:
private void tableLayoutPanelTest_MouseMove(object sender, MouseEventArgs e)
{
if (!placeShip)
{
c = tableLayoutPanelTest.GetControlFromPosition(homeLastPosition.Column, homeLastPosition.Row);
if (c.GetType() == typeof(PictureBox))
{
PictureBox hover = new PictureBox();
hover = (PictureBox)(c);
hover.Image = Properties.Resources.water;
}
Point p = tableLayoutPanelTest.PointToClient(Control.MousePosition);
Control picControl = tableLayoutPanelTest.GetChildAtPoint(p);
if (picControl != null)
{
TableLayoutPanelCellPosition me = tableLayoutPanelTest.GetCellPosition(picControl);
if (picControl.GetType() == typeof(PictureBox))
{
PictureBox thisLocation = new PictureBox();
thisLocation = (PictureBox)(picControl);
thisLocation.Image = Properties.Resources.scan;
homeLastPosition = me;
}
}
}
toolTipApp.SetToolTip(tableLayoutPanelTest, tableLayoutPanelTest.GetCellPosition(c).ToString());
}
when i run this the tooTipApp starts consuming upto 56% of the CPU. so there is something wrong.
also the picturebox image changing code stops working for some reason.
any help is very welcome!
thank you.
A few thoughts:
You're creating another PictureBox called hover - why? This code doesn't seem to do anything and it's almost certainly going to slow the loop down. I think you meant to just declare hover and cast it from c, but you're actually creating a new PictureBox instance and just throwing it away.
You're also never disposing of hover, as far as I can tell - so you end up allocating tons of memory and window handles. In general you should avoid creating new objects at all inside a MouseMove handler (small ones like hit tests are sometimes OK). As with the previous point - you probably didn't mean to write the new PictureBox().
You use PointToClient(Control.MousePosition) when the MouseMove event already gives you the control-specific mouse position (e.X and e.Y). This is costing you more time than it should.
Probably the most important, you're invoking SetToolTip on every MouseMove. You should only be invoking this when the tooltip has actually changed. You need to set a flag on which cell or control the tooltip was last displayed for, check for changes, then call SetToolTip.
You will get a lot of performance back if you avoid setting the tooltip text when it hasn't changed.
Other than that I want to echo the comment. This is a lot of processing for a mouse handler.
You should be trying to do an early test to see if the mouse is still over the same thing it was on the last move, and skipping most of the code in that case.

Categories

Resources