code_snippets:frameless_window_draggable
Table of Contents
Frameless Window Draggable
Below is a complete sample of the code needed to perform a frameless window with dragging capabilities.
public class Game1 : Game
{
private GraphicsDeviceManager _graphics;
private SpriteBatch _spriteBatch;
// Fields to track dragging state
private bool _isDragging = false;
private Point _dragOffset;
public Game1()
{
_graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
IsMouseVisible = true;
// Hide the window frame
Window.IsBorderless = true;
}
protected override void Initialize()
{
// TODO: Add your initialization logic here
base.Initialize();
}
protected override void LoadContent()
{
_spriteBatch = new SpriteBatch(GraphicsDevice);
// TODO: use this.Content to load your game content here
}
protected override void Update(GameTime gameTime)
{
if (GamePad.GetState(PlayerIndex.One).Buttons.Back ==
ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
Exit();
// Get the keyboard state
var keyboardState = Keyboard.GetState();
// If keyboard spacekey pressed toggle Window Borderless
if (keyboardState.IsKeyDown(Keys.Space))
{
Window.IsBorderless = !Window.IsBorderless;
}
// Handle window dragging only if the window frame is hidden
if (Window.IsBorderless)
{
var mouseState = Mouse.GetState();
if (mouseState.LeftButton == ButtonState.Pressed)
{
if (!_isDragging)
{
// Start dragging if the mouse is near the top of the window
if (mouseState.Y < 30) // Adjust the value as needed
{
_isDragging = true;
_dragOffset = new Point(mouseState.X, mouseState.Y);
}
}
else
{
// Move the window
var newPosition = new Point(mouseState.X -
_dragOffset.X, mouseState.Y - _dragOffset.Y);
Window.Position = new Point(Window.Position.X +
newPosition.X, Window.Position.Y + newPosition.Y);
}
}
else
{
_isDragging = false;
}
}
// TODO: Add your update logic here
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
// TODO: Add your drawing code here
base.Draw(gameTime);
}
}
Known Issues
When capturing the screen using Snippint Tool, with window frameless enabled, the game window will shift off screen, untested on a single display, but this throws it off screen onto another screen on a multi monitor setup. the window toggle was added to help remedy this.
code_snippets/frameless_window_draggable.txt · Last modified: 2024/09/24 08:19 by mrvalentine