Shake detection mouse - c#

My code is used to form1
private int X,Y;
private void timer1_Tick(object sender, EventArgs e)
{
if (this.X != Cursor.Position.X ||
this.Y != Cursor.Position.Y)
{
this.Form1_Load(this, e);
}
else
{
this.Text = (Convert.ToInt16(this.Text)+1).ToString();
}
}
private void Form1_Load(object sender, EventArgs e)
{
this.Text = "0";
this.X = Cursor.Position.X;
this.Y = Cursor.Position.Y;
}
Other forms will not answer
If the form2 is open. The above code does not work.

Well I am not sure what exactly want to accomplish, but try to set form2.Owner = this (if you show form2 from from1) or form2.Owner = form1.

This code for the screensaver :
//inForm1
[DllImport("user32.dll", EntryPoint = "GetDesktopWindow")]
private static extern IntPtr GetDesktopWindow();
[DllImport("user32.dll")]
private static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, int wParam, int lParam);
//...
private const int SC_SCREENSAVE = 0xF140;
private const int WM_SYSCOMMAND = 0x0112;
//...
public static void SetScreenSaverRunning()
{
SendMessage
(GetDesktopWindow(), WM_SYSCOMMAND, SC_SCREENSAVE, 0);
}
public void Shakedetectionmouse(EventArgs e)
{
//CallTimer1_Tick
timer1_Tick(this,e);
}
private void timer1_Tick(object sender, EventArgs e)
{
//ShowScreenSaver
timer1.Enabled = true;
timer1.Interval = 1000;
SetScreenSaverRunning();
}
private void button1_Click(object sender, EventArgs e)
{
//ShowForm2
using (var Form2 = new Form2())
{
Form2.ShowDialog();
}
}
//Inform2
private void Form2_Load(object sender, EventArgs e)
{
timer1.Enabled = true;
timer1.Interval = 2000;
}
private void timer1_Tick(object sender, EventArgs e)
{
using(var form1 = new Form1())
{
form1.Shakedetectionmouse(EventArgs.Empty);
}
}
In any form should be used Timer Component
Is it not a way to solve this issue?
screen saver Windows can be used?

Related

What is the right way to execute c# code in a powershell script?

I'm trying to play/pause media and I found some c# code but when I try to implement it into my powershell script, nothing happens... This is what I tried:
Add-Type #'
using System;
using System.Windows;
using System.Runtime.InteropServices;
namespace UniversalSandbox
{
public partial class Form1
{
public const int KEYEVENTF_EXTENTEDKEY = 1;
public const int KEYEVENTF_KEYUP = 0;
public const int VK_MEDIA_NEXT_TRACK = 0xB0;
public const int VK_MEDIA_PLAY_PAUSE = 0xB3;
public const int VK_MEDIA_PREV_TRACK = 0xB1;
[DllImport("user32.dll")]
public static extern void keybd_event(byte virtualKey, byte scanCode, uint flags, IntPtr extraInfo);
private void button1_Click(object sender, EventArgs e)
{
keybd_event(VK_MEDIA_PLAY_PAUSE, 0, KEYEVENTF_EXTENTEDKEY, IntPtr.Zero);
}
private void button2_Click(object sender, EventArgs e)
{
keybd_event(VK_MEDIA_PREV_TRACK, 0, KEYEVENTF_EXTENTEDKEY, IntPtr.Zero);
}
private void button3_Click(object sender, EventArgs e)
{
keybd_event(VK_MEDIA_NEXT_TRACK, 0, KEYEVENTF_EXTENTEDKEY, IntPtr.Zero);
}
}
}
'#
[UniversalSandbox.Form1]::button1_Click;
I call the play/pause event using [UniversalSandbox.Form1]::button1_Click; but nothing happens... Is my syntax wrong?
(I found the c# code here)
You example is a Windows Forms app. You need to add some extra buttons and create form instance (GUI) and click buttons to manipulate it. button1_click is event you need to assign to the button control (you can't call it directly). Below is updated example.
Add-Type #'
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Runtime.InteropServices;
namespace UniversalSandbox
{
public partial class Form1 : Form
{
public const int KEYEVENTF_EXTENTEDKEY = 1;
public const int KEYEVENTF_KEYUP = 0;
public const int VK_MEDIA_NEXT_TRACK = 0xB0;
public const int VK_MEDIA_PLAY_PAUSE = 0xB3;
public const int VK_MEDIA_PREV_TRACK = 0xB1;
[DllImport("user32.dll")]
public static extern void keybd_event(byte virtualKey, byte scanCode, uint flags, IntPtr extraInfo);
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void InitializeComponent(){
var button1 = new Button();
var button2 = new Button();
var button3 = new Button();
button1.Text = "Play";
button1.Location = new Point(20, 100);
button1.Click += new EventHandler(button1_Click);
button2.Text = "Prev";
button2.Location = new Point(110, 100);
button2.Click += new EventHandler(button2_Click);
button3.Text = "Next";
button3.Location = new Point(200, 100);
button3.Click += new EventHandler(button3_Click);
this.Controls.Add(button1);
this.Controls.Add(button2);
this.Controls.Add(button3);
}
private void button1_Click(object sender, EventArgs e)
{
keybd_event(VK_MEDIA_PLAY_PAUSE, 0, KEYEVENTF_EXTENTEDKEY, IntPtr.Zero);
}
private void button2_Click(object sender, EventArgs e)
{
keybd_event(VK_MEDIA_PREV_TRACK, 0, KEYEVENTF_EXTENTEDKEY, IntPtr.Zero);
}
private void button3_Click(object sender, EventArgs e)
{
keybd_event(VK_MEDIA_NEXT_TRACK, 0, KEYEVENTF_EXTENTEDKEY, IntPtr.Zero);
}
}
}
'# -ReferencedAssemblies System.Windows.Forms, System.Drawing
$player = [UniversalSandbox.Form1]::new()
$player.ShowDialog()
Mike Twc's answer shows an effective solution that adds many pieces that were missing from your code.
As for what you tried in terms of syntax:
[UniversalSandbox.Form1]::button1_Click
tries to access a static (::) public member named button1_Click.
If there were such a method (there isn't, because (a) you've made it an instance method and (b) you've made it private), accessing it without parentheses () (including required arguments) would print the method's signature (its return type, name, parameter names and types) rather than call it.

How to make a picturebox dragable?

I am an enthusiastic programmer and new to stack overflow.
I am trying to build a prototype of an OS(Operating System) in C#...Just a test.
Just like we see that we can drag things in the desktop and put it anywhere I am creating a desktop for my OS.
So how should I make an icon(a picturebox) drag-able and how would I save its position so that next time I open my desktop I see it in the same place?
I would love the dragging without any freezes or those sneaky bugs. I would love if, it is as close and smooth as the ones in Windows(dragging items(icons) in desktop)..
Thanks...
Yes, it is.
Assume a Picturebox named "pbxBigCat" (load it with a pPicture ...)
Add this lines to your form:
public const int WM_NCLBUTTONDOWN = 0xA1;
public const int HT_CAPTION = 0x2;
[DllImportAttribute("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
[DllImportAttribute("user32.dll")]
public static extern bool ReleaseCapture();
And then write an eventhandler for the pbxBigCat MouseDown event:
private void pbxBigCat_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
ReleaseCapture();
SendMessage(pbxBigCat.Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
}
}
If you test it you will se it works. For more Information (like saving positions etc.) I refere to Make a borderless form movable?
Another possibility to do this (now we have a Label called label1)
public partial class Form1 : Form
{
private bool mouseDown;
private Point lastLocation;
public Form1()
{
InitializeComponent();
}
private void pbxBigCat_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
mouseDown = true;
lastLocation = e.Location;
}
}
private void pbxBigCat_MouseMove(object sender, MouseEventArgs e)
{
if (mouseDown)
{
pbxBigCat.Location = new Point((pbxBigCat.Location.X - lastLocation.X + e.X), (pbxBigCat.Location.Y - lastLocation.Y) + e.Y);
label1.Text = pbxBigCat.Location.X.ToString() + "/" + pbxBigCat.Location.Y.ToString();
}
}
private void pbxBigCat_MouseUp(object sender, MouseEventArgs e)
{
mouseDown = false;
}
}
Everything drawn from the example on the mentioned SO article.

How to make multiselect listbox only with mouse in C# (Winform)?

I have listbox with some items in it, what I'm looking for this:
always previous items keep selected and if i click an item that isn't selected it get selected too but if it's already selected it get's unselected.
I used these code but it doesn't work very well!
here's my code(this one does not work at all):
public partial class Options_Form : Form
{
public Options_Form()
{
InitializeComponent();
}
private void Options_Load(object sender, EventArgs e)
{
AceMP_Class cl = new AceMP_Class();
listBox1.Items.AddRange(cl.SupportedFiles_stringarray());
listBox1.SelectionMode = SelectionMode.MultiExtended;
listBox1.Size = listBox1.PreferredSize;
listboxitemsState_array = new bool[cl.SupportedFiles_stringarray().Length];
}
private void button2_Click(object sender, EventArgs e)
{
listBox1.ClearSelected();
//selecteditemsindex_list.Clear();
}
//List<int> selecteditemsindex_list = new List<int>();
bool[] listboxitemsState_array;
private void listBox1_MouseDown(object sender, MouseEventArgs e)
{
for (int i = 0; i < listboxitemsState_array.Length; i++)
{
if (listboxitemsState_array[i])
{
listBox1.SetSelected(i, true);
}
else
{
listBox1.SetSelected(i, false);
}
}
//if (listBox1.GetSelected(listBox1.IndexFromPoint(e.X, e.Y)))
if (listboxitemsState_array[listBox1.IndexFromPoint(e.X, e.Y)])
{
listBox1.SetSelected(listBox1.IndexFromPoint(e.X, e.Y), false);
listboxitemsState_array[listBox1.IndexFromPoint(e.X, e.Y)] = false;
}
else
{
listBox1.SetSelected(listBox1.IndexFromPoint(e.X, e.Y), true);
listboxitemsState_array[listBox1.IndexFromPoint(e.X, e.Y)] = true;
}
}
private void listBox1_MouseUp(object sender, MouseEventArgs e)
{
for (int i = 0; i < listboxitemsState_array.Length; i++)
{
if (listboxitemsState_array[i])
{
listBox1.SetSelected(i, true);
}
else
{
listBox1.SetSelected(i, false);
}
}
//if (listBox1.GetSelected(listBox1.IndexFromPoint(e.X, e.Y)))
if (listboxitemsState_array[listBox1.IndexFromPoint(e.X, e.Y)])
{
listBox1.SetSelected(listBox1.IndexFromPoint(e.X, e.Y), false);
listboxitemsState_array[listBox1.IndexFromPoint(e.X, e.Y)] = false;
}
else
{
listBox1.SetSelected(listBox1.IndexFromPoint(e.X, e.Y), true);
listboxitemsState_array[listBox1.IndexFromPoint(e.X, e.Y)] = true;
}
}
}
but this one works but not very well!
public partial class Options_Form : Form
{
public Options_Form()
{
InitializeComponent();
}
private void Options_Load(object sender, EventArgs e)
{
AceMP_Class cl = new AceMP_Class();
listBox1.Items.AddRange(cl.SupportedFiles_stringarray());
listBox1.SelectionMode = SelectionMode.MultiExtended;
listBox1.Size = listBox1.PreferredSize;
}
private void button2_Click(object sender, EventArgs e)
{
listBox1.ClearSelected();
selecteditemsindex_list.Clear();
}
List<int> selecteditemsindex_list = new List<int>();
private void listBox1_Click(object sender, EventArgs e)
{
listBox1.ClearSelected();
}
private void listBox1_MouseDown(object sender, MouseEventArgs e)
{
for (int i = 0; i < selecteditemsindex_list.Count; i++)
{
listBox1.SetSelected(selecteditemsindex_list[i], true);
}
}
private void listBox1_MouseUp(object sender, MouseEventArgs e)
{
for (int i = 0; i < selecteditemsindex_list.Count; i++)
{
listBox1.SetSelected(selecteditemsindex_list[i], true);
}
if (listBox1.GetSelected(listBox1.IndexFromPoint(e.X, e.Y)))
{
listBox1.SetSelected(listBox1.IndexFromPoint(e.X, e.Y), false);
}
else
{
listBox1.SetSelected(listBox1.IndexFromPoint(e.X, e.Y), true);
selecteditemsindex_list.Add(listBox1.IndexFromPoint(e.X, e.Y));
}
}
}
How can I solve that!?
I want to mention that you achieved this feature with SelectionMode.MultiExtended but you need to press CTRL + Click or SHIFT + Click.
To achieve this only with mouse:
1) A better solution comes up as when i discuss with #ACE (he come up with idea to use virtualkey) is to press CTRL key when you make clicks. On MouseDown you press CTRL and on MouseUp release the CTRL key.
public partial class Options_Form : Form
{
public Options_Form()
{
InitializeComponent();
}
private void Options_Load(object sender, EventArgs e)
{
AceMP_Class cl = new AceMP_Class();
listBox1.Items.AddRange(cl.SupportedFiles_stringarray());
listBox1.SelectionMode = SelectionMode.MultiSimple;
listBox1.Size = listBox1.PreferredSize;
}
[DllImport("user32.dll", SetLastError = true)]
static extern void keybd_event(byte bVk, byte bScan, int dwFlags, int dwExtraInfo);
public const uint KEYEVENTF_KEYUP = 0x02;
public const uint VK_CONTROL = 0x11;
private void listBox1_MouseDown(object sender, MouseEventArgs e)
{
keybd_event(Convert.ToByte(VK_CONTROL), 0, 0, 0);
}
private void listBox1_MouseUp(object sender, MouseEventArgs e)
{
keybd_event(Convert.ToByte(VK_CONTROL), 0, Convert.ToByte(KEYEVENTF_KEYUP), 0);
}
}
2) The easiest solution that comes up in my mind (with some drawbacks if you pres click very fast) is to use on MouseClick event and to have an array of bool that every index from that array tells me if selected or not.
selecteditemsindex_list[selectedIndex] = !selecteditemsindex_list[selectedIndex];
How it works?
Take the current index and negate (!) the value at that index. This way you obtain select/unselect feature with mouse.
Because i work only with the current index the others values from array remains unmodified and i can use SetSelected for all values from array. This way you can make multiselect with mouse.
public partial class Options_Form : Form
{
public Options_Form()
{
InitializeComponent();
}
bool[] selecteditemsindex_list;
private void Options_Load(object sender, EventArgs e)
{
AceMP_Class cl = new AceMP_Class();
listBox1.Items.AddRange(cl.SupportedFiles_stringarray());
listBox1.SelectionMode = SelectionMode.MultiExtended;
listBox1.Size = listBox1.PreferredSize;
selecteditemsindex_list = new bool[listBox1.Items.Count];
}
private void listBox1_MouseDown(object sender, MouseEventArgs e)
{
var selectedIndex = listBox1.SelectedIndex;
selecteditemsindex_list[selectedIndex] = !selecteditemsindex_list[selectedIndex];
for (int i = 0; i < selecteditemsindex_list.Count(); i++)
{
listBox1.SetSelected(i, selecteditemsindex_list[i]);
}
}
}
The ListBox control has a property 'SelectionMode'
You can set it to :
One
MultiSimple
MultiExtended
see this link for details

Creating custom pop up keyboard nothing happen when keys are press

What I want to happen is that when a textbox is clicked a pop up keyboard will show and whatever i type on the keyboard will be putt in the textbox, but nothing happen but when I use notepad, it works. How can I fix this?
Here is my main form code:
private void textBox1_MouseClick(object sender, MouseEventArgs e)
{
Form1 frm1 = new Form1();
frm1.ShowDialog();
}
And here is my code for pop up keyboard
public partial class Form1 : Form
{
const int WS_EX_NOACTIVATE = 0x08000000;
//this line of code fixed the issue
[DllImport("user32.dll", EntryPoint = "GetDesktopWindow")]
public static extern IntPtr GetDesktopWindow();
public Form1()
{
InitializeComponent();
}
protected override CreateParams CreateParams
{
get
{
CreateParams param = base.CreateParams;
param.ExStyle |= WS_EX_NOACTIVATE;
//This line of code fix the issues
param.Style = 0x40000000 | 0x4000000;
param.Parent = GetDesktopWindow();
return param;
}
}
private void button1_Click(object sender, EventArgs e)
{
SendKeys.Send("1");
}
private void button3_Click(object sender, EventArgs e)
{
SendKeys.Send("2");
}
private void button4_Click(object sender, EventArgs e)
{
SendKeys.Send("3");
}
private void button2_Click(object sender, EventArgs e)
{
}
}
Use form1.Show() ... not ShowDialog()
If you manually added the testbox make sure you hook into the MouseEventHandler like so:
this.textBox1.MouseClick += new System.Windows.Forms.MouseEventHandler(this.textBox1_MouseClick);
when your form loads.
I fixed the issue by just adding this line of code
[DllImport("user32.dll", EntryPoint = "GetDesktopWindow")]
public static extern IntPtr GetDesktopWindow();
And
param.Style = 0x40000000 | 0x4000000;
param.Parent = GetDesktopWindow();

Make a borderless form movable?

Is there a way to make a form that has no border (FormBorderStyle is set to "none") movable when the mouse is clicked down on the form just as if there was a border?
This article on CodeProject details a technique. Is basically boils down to:
public const int WM_NCLBUTTONDOWN = 0xA1;
public const int HT_CAPTION = 0x2;
[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern bool ReleaseCapture();
private void Form1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
ReleaseCapture();
SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
}
}
This essentially does exactly the same as grabbing the title bar of a window, from the window manager's point of view.
Let's not make things any more difficult than they need to be. I've come across so many snippets of code that allow you to drag a form around (or another Control). And many of them have their own drawbacks/side effects. Especially those ones where they trick Windows into thinking that a Control on a form is the actual form.
That being said, here is my snippet. I use it all the time. I'd also like to note that you should not use this.Invalidate(); as others like to do because it causes the form to flicker in some cases. And in some cases so does this.Refresh. Using this.Update, I have not had any flickering issues:
private bool mouseDown;
private Point lastLocation;
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
mouseDown = true;
lastLocation = e.Location;
}
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
if(mouseDown)
{
this.Location = new Point(
(this.Location.X - lastLocation.X) + e.X, (this.Location.Y - lastLocation.Y) + e.Y);
this.Update();
}
}
private void Form1_MouseUp(object sender, MouseEventArgs e)
{
mouseDown = false;
}
Another simpler way to do the same thing.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
// set this.FormBorderStyle to None here if needed
// if set to none, make sure you have a way to close the form!
}
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
if (m.Msg == WM_NCHITTEST)
m.Result = (IntPtr)(HT_CAPTION);
}
private const int WM_NCHITTEST = 0x84;
private const int HT_CLIENT = 0x1;
private const int HT_CAPTION = 0x2;
}
use MouseDown, MouseMove and MouseUp. You can set a variable flag for that. I have a sample, but I think you need to revise.
I am coding the mouse action to a panel. Once you click the panel, your form will move with it.
//Global variables;
private bool _dragging = false;
private Point _offset;
private Point _start_point=new Point(0,0);
private void panel1_MouseDown(object sender, MouseEventArgs e)
{
_dragging = true; // _dragging is your variable flag
_start_point = new Point(e.X, e.Y);
}
private void panel1_MouseUp(object sender, MouseEventArgs e)
{
_dragging = false;
}
private void panel1_MouseMove(object sender, MouseEventArgs e)
{
if(_dragging)
{
Point p = PointToScreen(e.Location);
Location = new Point(p.X - this._start_point.X,p.Y - this._start_point.Y);
}
}
WPF only
don't have the exact code to hand, but in a recent project I think I used MouseDown event and simply put this:
frmBorderless.DragMove();
Window.DragMove Method (MSDN)
It worked for Me.
private Point _mouseLoc;
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
_mouseLoc = e.Location;
}
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
int dx = e.Location.X - _mouseLoc.X;
int dy = e.Location.Y - _mouseLoc.Y;
this.Location = new Point(this.Location.X + dx, this.Location.Y + dy);
}
}
Ref. video Link
This is tested and easy to understand.
protected override void WndProc(ref Message m)
{
switch (m.Msg)
{
case 0x84:
base.WndProc(ref m);
if((int)m.Result == 0x1)
m.Result = (IntPtr)0x2;
return;
}
base.WndProc(ref m);
}
Since some answers do not allow for child controls to be draggable, I've created a little helper class.
It should be passed the top level form. Can be made more generic if desired.
class MouseDragger
{
private readonly Form _form;
private Point _mouseDown;
protected void OnMouseDown(object sender, MouseEventArgs e)
{
_mouseDown = e.Location;
}
protected void OnMouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
int dx = e.Location.X - _mouseDown.X;
int dy = e.Location.Y - _mouseDown.Y;
_form.Location = new Point(_form.Location.X + dx, _form.Location.Y + dy);
}
}
public MouseDragger(Form form)
{
_form = form;
MakeDraggable(_form);
}
private void MakeDraggable(Control control)
{
var type = control.GetType();
if (typeof(Button).IsAssignableFrom(type))
{
return;
}
control.MouseDown += OnMouseDown;
control.MouseMove += OnMouseMove;
foreach (Control child in control.Controls)
{
MakeDraggable(child);
}
}
}
There's no property you can flip to make this just happen magically. Look at the events for the form and it becomes fairly trivial to implement this by setting this.Top and this.Left. Specifically you'll want to look at MouseDown, MouseUp and MouseMove.
public Point mouseLocation;
private void frmInstallDevice_MouseDown(object sender, MouseEventArgs e)
{
mouseLocation = new Point(-e.X, -e.Y);
}
private void frmInstallDevice_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
Point mousePos = Control.MousePosition;
mousePos.Offset(mouseLocation.X, mouseLocation.Y);
Location = mousePos;
}
}
this can solve ur problem....
https://social.msdn.microsoft.com/Forums/vstudio/en-US/d803d869-68e6-46ff-9ff1-fabf78d6393c/how-to-make-a-borderless-form-in-c?forum=csharpgeneral
This bit of code from the above link did the trick in my case :)
protected override void OnMouseDown(MouseEventArgs e)
{
base.OnMouseDown(e);
if (e.Button == MouseButtons.Left)
{
this.Capture = false;
Message msg = Message.Create(this.Handle, 0XA1, new IntPtr(2), IntPtr.Zero);
this.WndProc(ref msg);
}
}
Best way I've found (modified of course)
// This adds the event handler for the control
private void AddDrag(Control Control) { Control.MouseDown += new System.Windows.Forms.MouseEventHandler(this.DragForm_MouseDown); }
public const int WM_NCLBUTTONDOWN = 0xA1;
public const int HT_CAPTION = 0x2;
[System.Runtime.InteropServices.DllImportAttribute("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
[System.Runtime.InteropServices.DllImportAttribute("user32.dll")]
public static extern bool ReleaseCapture();
private void DragForm_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
ReleaseCapture();
SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
// Checks if Y = 0, if so maximize the form
if (this.Location.Y == 0) { this.WindowState = FormWindowState.Maximized; }
}
}
To apply drag to a control simply insert this after InitializeComponent()
AddDrag(NameOfControl);
For .NET Framework 4,
You can use this.DragMove() for the MouseDown event of the component (mainLayout in this example) you are using to drag.
private void mainLayout_MouseDown(object sender, MouseButtonEventArgs e)
{
this.DragMove();
}
Easiest way is:
First create a label named label1.
Go to label1's events > mouse events > Label1_Mouse Move and write these:
if (e.Button == MouseButtons.Left){
Left += e.X;
Top += e.Y;`
}
I was trying to make a borderless windows form movable which contained a WPF Element Host control and a WPF User control.
I ended up with a stack panel called StackPanel in my WPF user control which seemed the logical thing to try click on to move. Trying junmats's code worked when I moved the mouse slowly, but if I moved the mouse faster, the mouse would move off the form and the form would be stuck somewhere mid move.
This improved on his answer for my situation using CaptureMouse and ReleaseCaptureMouse and now the mouse does not move off the form while moving it even if I move it quickly.
private void StackPanel_MouseDown(object sender, MouseButtonEventArgs e)
{
_start_point = e.GetPosition(this);
StackPanel.CaptureMouse();
}
private void StackPanel_MouseUp(object sender, MouseButtonEventArgs e)
{
StackPanel.ReleaseMouseCapture();
}
private void StackPanel_MouseMove(object sender, MouseEventArgs e)
{
if (StackPanel.IsMouseCaptured)
{
var p = _form.GetMousePositionWindowsForms();
_form.Location = new System.Drawing.Point((int)(p.X - this._start_point.X), (int)(p.Y - this._start_point.Y));
}
}
//Global variables;
private Point _start_point = new Point(0, 0);
I'm expanding the solution from jay_t55 with one more method ToolStrip1_MouseLeave that handles the event of the mouse moving quickly and leaving the region.
private bool mouseDown;
private Point lastLocation;
private void ToolStrip1_MouseDown(object sender, MouseEventArgs e) {
mouseDown = true;
lastLocation = e.Location;
}
private void ToolStrip1_MouseMove(object sender, MouseEventArgs e) {
if (mouseDown) {
this.Location = new Point(
(this.Location.X - lastLocation.X) + e.X, (this.Location.Y - lastLocation.Y) + e.Y);
this.Update();
}
}
private void ToolStrip1_MouseUp(object sender, MouseEventArgs e) {
mouseDown = false;
}
private void ToolStrip1_MouseLeave(object sender, EventArgs e) {
mouseDown = false;
}
Also if you need to DoubleClick and make your Form bigger/smaller , you can use the First answer, create a global int variable, add 1 every time user clicks on the component you use for dragging. If variable == 2 then make your form bigger/smaller. Also use a timer for every half a sec or a second to make your variable = 0;
Adding a MouseLeftButtonDown event handler to the MainWindow worked for me.
In the event function that gets automatically generated, add the below code:
base.OnMouseLeftButtonDown(e);
this.DragMove();
Form1(): new Moveable(control1, control2, control3);
Class:
using System;
using System.Windows.Forms;
class Moveable
{
public const int WM_NCLBUTTONDOWN = 0xA1;
public const int HT_CAPTION = 0x2;
[System.Runtime.InteropServices.DllImportAttribute("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
[System.Runtime.InteropServices.DllImportAttribute("user32.dll")]
public static extern bool ReleaseCapture();
public Moveable(params Control[] controls)
{
foreach (var ctrl in controls)
{
ctrl.MouseDown += (s, e) =>
{
if (e.Button == MouseButtons.Left)
{
ReleaseCapture();
SendMessage(ctrl.FindForm().Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
// Checks if Y = 0, if so maximize the form
if (ctrl.FindForm().Location.Y == 0) { ctrl.FindForm().WindowState = FormWindowState.Maximized; }
}
};
}
}
}
I tried the following and presto changeo, my transparent window was no longer frozen in place but could be moved!! (throw away all those other complex solutions above...)
private void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
base.OnMouseLeftButtonDown(e);
// Begin dragging the window
this.DragMove();
}

Categories