C# - SendKeys GUI Buttons Bug - winforms

I've downloaded a spammer program from YouTube, and decompiled it. Here's the code:
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;
namespace SimpleSpammer
{
public class Form1 : Form
{
private IContainer components;
private TextBox textBox1;
private Button button1;
private Button button2;
private Label label1;
private LinkLabel linkLabel1;
private Label label2;
private LinkLabel linkLabel2;
private Label label3;
private Timer timer1;
private Label label4;
private TextBox textBox2;
private Label label5;
private CheckBox checkBox1;
public Form1()
{
this.components = (IContainer) null;
base.\u002Ector();
this.InitializeComponent();
}
protected override void Dispose(bool disposing)
{
if (disposing && this.components != null)
this.components.Dispose();
base.Dispose(disposing);
}
private void InitializeComponent()
{
this.components = (IContainer) new Container();
this.textBox1 = new TextBox();
this.button1 = new Button();
this.button2 = new Button();
this.label1 = new Label();
this.linkLabel1 = new LinkLabel();
this.label2 = new Label();
this.linkLabel2 = new LinkLabel();
this.label3 = new Label();
this.timer1 = new Timer(this.components);
this.label4 = new Label();
this.textBox2 = new TextBox();
this.label5 = new Label();
this.checkBox1 = new CheckBox();
this.SuspendLayout();
this.textBox1.Location = new Point(13, 13);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new Size(259, 20);
this.textBox1.TabIndex = 0;
this.textBox1.Text = "SPAM !";
this.textBox1.TextAlign = HorizontalAlignment.Center;
this.button1.Location = new Point(13, 39);
this.button1.Name = "button1";
this.button1.Size = new Size(75, 23);
this.button1.TabIndex = 1;
this.button1.Text = "Start";
this.button1.UseVisualStyleBackColor = true;
// ISSUE: method pointer
this.button1.Click += new EventHandler((object) this, __methodptr(button1_Click));
this.button2.Location = new Point(197, 39);
this.button2.Name = "button2";
this.button2.Size = new Size(75, 23);
this.button2.TabIndex = 2;
this.button2.Text = "Stop";
this.button2.UseVisualStyleBackColor = true;
// ISSUE: method pointer
this.button2.Click += new EventHandler((object) this, __methodptr(button2_Click));
this.label1.AutoSize = true;
this.label1.Font = new Font("Arial", 8.25f, FontStyle.Italic, GraphicsUnit.Point, (byte) 0);
this.label1.ForeColor = SystemColors.WindowFrame;
this.label1.Location = new Point(7, 216);
this.label1.Name = "label1";
this.label1.Size = new Size(275, 14);
this.label1.TabIndex = 3;
this.label1.Text = "Copyright © 2010 TheDarkJoker94. This is a freeware.";
this.linkLabel1.AutoSize = true;
this.linkLabel1.Location = new Point(30, 190);
this.linkLabel1.Name = "linkLabel1";
this.linkLabel1.Size = new Size(162, 13);
this.linkLabel1.TabIndex = 4;
this.linkLabel1.TabStop = true;
this.linkLabel1.Text = "http://thedarkjoker94.cer33.com";
// ISSUE: method pointer
this.linkLabel1.LinkClicked += new LinkLabelLinkClickedEventHandler((object) this, __methodptr(linkLabel1_LinkClicked));
this.label2.AutoSize = true;
this.label2.Location = new Point(10, 135);
this.label2.Name = "label2";
this.label2.Size = new Size(172, 13);
this.label2.TabIndex = 5;
this.label2.Text = "Check my C# Tutorials on Youtube";
this.linkLabel2.AutoSize = true;
this.linkLabel2.Location = new Point(30, 151);
this.linkLabel2.Name = "linkLabel2";
this.linkLabel2.Size = new Size(242, 13);
this.linkLabel2.TabIndex = 6;
this.linkLabel2.TabStop = true;
this.linkLabel2.Text = "http://www.youtube.com/user/TheDarkJoker094";
// ISSUE: method pointer
this.linkLabel2.LinkClicked += new LinkLabelLinkClickedEventHandler((object) this, __methodptr(linkLabel2_LinkClicked));
this.label3.AutoSize = true;
this.label3.Location = new Point(10, 171);
this.label3.Name = "label3";
this.label3.Size = new Size(91, 13);
this.label3.TabIndex = 7;
this.label3.Text = "More Software on";
this.timer1.Interval = 500;
// ISSUE: method pointer
this.timer1.Tick += new EventHandler((object) this, __methodptr(timer1_Tick));
this.label4.AutoSize = true;
this.label4.Font = new Font("Arial", 9.75f, FontStyle.Regular, GraphicsUnit.Point, (byte) 0);
this.label4.Location = new Point(13, 73);
this.label4.Name = "label4";
this.label4.Size = new Size(88, 16);
this.label4.TabIndex = 8;
this.label4.Text = "Timer Interval:";
this.textBox2.Location = new Point(102, 72);
this.textBox2.Name = "textBox2";
this.textBox2.Size = new Size(89, 20);
this.textBox2.TabIndex = 9;
this.textBox2.Text = "100";
this.label5.AutoSize = true;
this.label5.Font = new Font("Arial", 9.75f, FontStyle.Regular, GraphicsUnit.Point, (byte) 0);
this.label5.Location = new Point(197, 73);
this.label5.Name = "label5";
this.label5.Size = new Size(77, 16);
this.label5.TabIndex = 10;
this.label5.Text = "miliseconds";
this.checkBox1.AutoSize = true;
this.checkBox1.Checked = true;
this.checkBox1.CheckState = CheckState.Checked;
this.checkBox1.Font = new Font("Arial", 9.75f, FontStyle.Regular, GraphicsUnit.Point, (byte) 0);
this.checkBox1.Location = new Point(13, 103);
this.checkBox1.Name = "checkBox1";
this.checkBox1.Size = new Size(151, 20);
this.checkBox1.TabIndex = 12;
this.checkBox1.Text = "Send the ENTER key";
this.checkBox1.UseVisualStyleBackColor = true;
this.AutoScaleDimensions = new SizeF(6f, 13f);
this.AutoScaleMode = AutoScaleMode.Font;
this.ClientSize = new Size(284, 239);
this.Controls.Add((Control) this.checkBox1);
this.Controls.Add((Control) this.label5);
this.Controls.Add((Control) this.textBox2);
this.Controls.Add((Control) this.label4);
this.Controls.Add((Control) this.label3);
this.Controls.Add((Control) this.linkLabel2);
this.Controls.Add((Control) this.label2);
this.Controls.Add((Control) this.linkLabel1);
this.Controls.Add((Control) this.label1);
this.Controls.Add((Control) this.button2);
this.Controls.Add((Control) this.button1);
this.Controls.Add((Control) this.textBox1);
this.FormBorderStyle = FormBorderStyle.FixedSingle;
this.MaximizeBox = false;
this.Name = "Form1";
this.ShowIcon = false;
this.Text = "SimpleSpammer";
this.ResumeLayout(false);
this.PerformLayout();
}
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
Process.Start("http://thedarkjoker94.cer33.com/");
}
private void button1_Click(object sender, EventArgs e)
{
try
{
this.timer1.Interval = Convert.ToInt32(this.textBox2.Text);
this.timer1.Start();
}
catch (Exception ex)
{
int num = (int) MessageBox.Show("An Exception was thrown!\n" + ex.Message, "ExceptionThrown");
}
}
private void timer1_Tick(object sender, EventArgs e)
{
if (this.Focused)
return;
SendKeys.Send(this.textBox1.Text);
if (this.checkBox1.CheckState == CheckState.Checked)
SendKeys.Send("{ENTER}");
}
private void button2_Click(object sender, EventArgs e)
{
this.timer1.Stop();
}
private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
Process.Start("http://www.youtube.com/user/TheDarkJoker094");
}
}
}
Now, as you can see his code contains a delay field, a text field, and "Start"/"Stop" buttons.
So I've tried to make something similar, and here's the code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace Spammer
{
public partial class Form1 : Form
{
int delay, y = 1;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
delay = int.Parse(textBox2.Text);
timer1.Interval = delay;
timer1.Start();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
timer1.Stop();
}
private void send()
{
}
private void label1_Click(object sender, EventArgs e)
{
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
private void timer1_Tick(object sender, EventArgs e)
{
if (this.Focused)
{
return;
}
SendKeys.Send(textBox1.Text);
}
}
}
Now, I've posted a similar question yesterday but this one is far more accurate.
In his program, I've entered some text, chose a delay of 10MS and started it. After a few seconds of sending, I've clicked the "Stop" button in his program and it stopped sending keys immediately.
Now... When I ran my program, and started sending keys (with a 10MS delay), I let it run for a few seconds, and then I pressed "Stop". Nothing happened, and "Stop" didn't even click. It just has shown a blue frame around it and I wasn't able to click it.
And of course, because of this, it didn't stop sending keys.
So, why did it work perfectly in his program but it doesn't work at all in my program?

Related

How to setup and connect to database in .net 6 winform project?

I'm new to Winform (.net 6), can anyone please show me a sample code on how to set up and connect to a database (SqlServer or MySQL) in Winform? Thanks!
Here is the link to a begginers guide to accessing SQL Server through C#.
The example usage to
set up and connect to a database (SqlServer or MySQL) in Winform
I give you here:
Form1.Designer
public partial class Form1
{
private System.ComponentModel.IContainer components = null;
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
private void InitializeComponent()
{
this.label1 = new System.Windows.Forms.Label();
this.textBox_dbAddress = new System.Windows.Forms.TextBox();
this.textBox_dbName = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.textBox_login = new System.Windows.Forms.TextBox();
this.label3 = new System.Windows.Forms.Label();
this.textBox_password = new System.Windows.Forms.TextBox();
this.label4 = new System.Windows.Forms.Label();
this.button1 = new System.Windows.Forms.Button();
this.SuspendLayout();
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(180, 88);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(132, 15);
this.label1.TabIndex = 0;
this.label1.Text = "Database server address";
this.textBox_dbAddress.Location = new System.Drawing.Point(180, 106);
this.textBox_dbAddress.Name = "textBox_dbAddress";
this.textBox_dbAddress.Size = new System.Drawing.Size(188, 23);
this.textBox_dbAddress.TabIndex = 1;
this.textBox_dbName.Location = new System.Drawing.Point(180, 153);
this.textBox_dbName.Name = "textBox_dbName";
this.textBox_dbName.Size = new System.Drawing.Size(188, 23);
this.textBox_dbName.TabIndex = 3;
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(180, 135);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(88, 15);
this.label2.TabIndex = 2;
this.label2.Text = "Database name";
this.textBox_login.Location = new System.Drawing.Point(180, 198);
this.textBox_login.Name = "textBox_login";
this.textBox_login.Size = new System.Drawing.Size(188, 23);
this.textBox_login.TabIndex = 5;
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(180, 180);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(37, 15);
this.label3.TabIndex = 4;
this.label3.Text = "Login";
this.textBox_password.Location = new System.Drawing.Point(180, 245);
this.textBox_password.Name = "textBox_password";
this.textBox_password.PasswordChar = '*';
this.textBox_password.Size = new System.Drawing.Size(188, 23);
this.textBox_password.TabIndex = 7;
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(180, 227);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(57, 15);
this.label4.TabIndex = 6;
this.label4.Text = "Password";
this.button1.Location = new System.Drawing.Point(180, 286);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 8;
this.button1.Text = "Connect";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Controls.Add(this.button1);
this.Controls.Add(this.textBox_password);
this.Controls.Add(this.label4);
this.Controls.Add(this.textBox_login);
this.Controls.Add(this.label3);
this.Controls.Add(this.textBox_dbName);
this.Controls.Add(this.label2);
this.Controls.Add(this.textBox_dbAddress);
this.Controls.Add(this.label1);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private Label label1;
private TextBox textBox_dbAddress;
private TextBox textBox_dbName;
private Label label2;
private TextBox textBox_login;
private Label label3;
private TextBox textBox_password;
private Label label4;
private Button button1;
}
Form1
public partial class Form1 : Form
{
public Form1()
{
this.InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
SqlConnection myConnection = new SqlConnection(
$"server={this.textBox_dbAddress.Text};" +
$"database={this.textBox_dbName.Text}; " +
$"user id={this.textBox_login.Text};" +
$"password={this.textBox_password.Text};" +
$"Trusted_Connection=yes;" +
$"connection timeout=30");
try
{
myConnection.Open();
MessageBox.Show("Connection oppened");
}
catch
{
MessageBox.Show("Connection failed");
}
finally
{
myConnection.Close();
}
}
}

ChromiumWebBrowser flash black after hiding without disabling WebGL

I am trying to hide my ChromiumWebBrowser behind images, video, etc... But every time it changes from a ChromiumWebBrowser to anything else than a blank panel or another ChromiumWebBrowser it flashes black for a few frames.
Exemple of my problem
hardware:
i7-8559U
intel IRI plus Graphics 655
CefSharp Version 79.1.350 for a Winform Program
Here is what I tried:
BringToFront other PictureBox
SendToback the ChromiumWebBrowser
Panel visibility
Panel doubleBuffed
I also enable Cef.EnableHighDPISupport(); but to no success.
The only thing that worked so far is to ADD
SetOffScreenRenderingBestPerformanceArgs();
But unfortunately, it disables WebGL implementation :/ and I would like to keep it for later purposes.
static class Program
{
/// <summary>
/// Point d'entrée principal de l'application.
/// </summary>
[STAThread]
static void Main()
{
Cef.EnableHighDPISupport();
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
public partial class Form1 : Form
{
private static ChromiumWebBrowser chrome;
private PictureBox ImageBox = new PictureBox();
private Panel pPictureBox = new Panel();
private Panel pChromium = new Panel();
Timer timer = new Timer();
public Form1()
{
InitializeComponent();
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Form1_FormClosing);
ImageBox.Image = Properties.Resources._3080;
ImageBox.SizeMode = PictureBoxSizeMode.StretchImage;
pPictureBox.Controls.Add(ImageBox);
ImageBox.Dock = DockStyle.Fill;
pPictureBox.Dock = DockStyle.Fill;
pPictureBox.Size = this.Size;
this.Controls.Add(pPictureBox);
pPictureBox.BringToFront();
InitializeChromium();
timer.Interval = 7000;
timer.Start();
timer.Tick += Timer_Tick;
}
private void Timer_Tick(object sender, EventArgs e)
{
if (pChromium.Visible)
{
pChromium.Hide();
}
else
{
pChromium.Show();
}
}
private void InitializeChromium()
{
pChromium.Dock = DockStyle.Fill;
pChromium.Size = this.Size;
CefSettings settings = new CefSettings();
//Work but disable WebGL
//settings.SetOffScreenRenderingBestPerformanceArgs();
//settings.DisableGpuAcceleration();
Cef.Initialize(settings);
chrome = new ChromiumWebBrowser("https://www.apple.com/ca/airpods-pro/");
pChromium.Controls.Add(chrome);
this.Controls.Add(pChromium);
chrome.Dock = DockStyle.Fill;
pChromium.BringToFront();
}
private void InitializeComponent()
{
this.SuspendLayout();
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.White;
this.ClientSize = new System.Drawing.Size(1904, 1041);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
Cef.Shutdown();
}
}
Do you guys have any solution?
Here is my final code for any one interested
Links of the command recommanded by #amaitland
https://peter.sh/experiments/chromium-command-line-switches/#use-angle
https://peter.sh/experiments/chromium-command-line-switches/#in-process-gpu
both command works individualy
Cef.EnableHighDPISupport(); is not required but is recommanded
static void Main()
{
Cef.EnableHighDPISupport();
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
public partial class Form1 : Form
{
private static ChromiumWebBrowser chrome;
private PictureBox ImageBox = new PictureBox();
private Panel pPictureBox = new Panel();
private Panel pChromium = new Panel();
Timer timer = new Timer();
public Form1()
{
InitializeComponent();
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Form1_FormClosing);
//any image here
ImageBox.Image = Properties.Resources._3080;
ImageBox.SizeMode = PictureBoxSizeMode.StretchImage;
pPictureBox.Controls.Add(ImageBox);
ImageBox.Dock = DockStyle.Fill;
pPictureBox.Dock = DockStyle.Fill;
pPictureBox.Size = this.Size;
this.Controls.Add(pPictureBox);
pPictureBox.BringToFront();
InitializeChromium();
timer.Interval = 7000;
timer.Start();
timer.Tick += Timer_Tick;
}
private void Timer_Tick(object sender, EventArgs e)
{
if (pChromium.Visible)
{
pChromium.Hide();
}
else
{
pChromium.Show();
}
}
private void InitializeChromium()
{
pChromium.Dock = DockStyle.Fill;
pChromium.Size = this.Size;
CefSettings settings = new CefSettings();
//-------------------------------------------------------------------------
settings.CefCommandLineArgs.Add("in-process-gpu");
//got best FPS with this renderer on "my machine"
settings.CefCommandLineArgs.Add("use-angle", "gl");
//-------------------------------------------------------------------------
//Work but disable WebGL
//settings.SetOffScreenRenderingBestPerformanceArgs();
//settings.DisableGpuAcceleration();
Cef.Initialize(settings);
chrome = new ChromiumWebBrowser("https://alteredqualia.com/three/examples/webgl_pasta.html");
pChromium.Controls.Add(chrome);
this.Controls.Add(pChromium);
chrome.Dock = DockStyle.Fill;
pChromium.BringToFront();
}
private void InitializeComponent()
{
this.SuspendLayout();
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.White;
this.ClientSize = new System.Drawing.Size(1904, 1041);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
Cef.Shutdown();
}
}

How to enable and disable dragging a button?

I have a form. On this form there is a button and a panel. Both have the same parent: the form. I want to be able to enable or disable the dragging operation of the button. The code I am using is:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace DraggableControls
{
public partial class Form2 : Form
{
private bool isDragged;
private Point pointOffset;
public Form2()
{
InitializeComponent();
this.Size = new System.Drawing.Size(800, 800);
this.AllowDrop = false;
Button button1 = new Button();
button1.Location = new Point(50, 50);
button1.BackColor = Color.Red;
button1.Size = new System.Drawing.Size(80, 80);
button1.Parent = this;
button1.AllowDrop = false;
button1.Draggable(false);
this.Controls.Add(button1);
isDragged = false;
// For the object that will be dragged:
button1.MouseDown += new MouseEventHandler(button1_MouseDown);
button1.MouseMove += new MouseEventHandler(button1_MouseMove);
button1.MouseUp += new MouseEventHandler(button1_MouseUp);
Panel panel1 = new Panel();
panel1.SuspendLayout();
panel1.Location = new System.Drawing.Point(100, 100);
panel1.Name = "panel1";
panel1.TabIndex = 0;
panel1.Size = new Size(500, 500);
panel1.BackColor = Color.Green;
panel1.AllowDrop = true;
panel1.Parent = this;
this.Controls.Add(panel1);
panel1.ResumeLayout(false);
// For the receiving object:
panel1.DragEnter += new
System.Windows.Forms.DragEventHandler(control_DragEnter);
this.DragEnter += new
System.Windows.Forms.DragEventHandler(control_DragEnter);
this.ResumeLayout(false);
}
private void button1_MouseDown(object sender, MouseEventArgs e)
{
if (sender is Button)
{
Button senderButton = (Button)sender;
if (e.Button == MouseButtons.Left)
{
isDragged = true;
Point ptStartPosition = senderButton.PointToScreen(new
Point(e.X, e.Y));
pointOffset = new Point();
pointOffset.X = senderButton.Location.X - ptStartPosition.X;
pointOffset.Y = senderButton.Location.Y - ptStartPosition.Y;
}
else
{
isDragged = false;
}
}
}
private void button1_MouseMove(object sender, MouseEventArgs e)
{
if (sender is Button)
{
Button senderButton = (Button)sender;
if (isDragged)
{
Point newPoint = senderButton.PointToScreen(new Point(e.X,
e.Y));
newPoint.Offset(pointOffset);
senderButton.Location = newPoint;
}
}
}
private void button1_MouseUp(object sender, MouseEventArgs e)
{
if (sender is Button)
{
Button senderButton = (Button)sender;
Point newPoint = senderButton.PointToScreen(new Point(e.X,
e.Y));
isDragged = false;
}
}
private void control_DragEnter(object sender, DragEventArgs e)
{
e.Effect = DragDropEffects.None;
}
/// <summary>
/// Prevents Window and any of the controls from being dragged by means
of the mouse.
/// </summary>
/// <param name="message"></param>
protected override void WndProc(ref Message message)
{
int WM_NCLBUTTONDOWN = 0xA1;
int WM_SYSCOMMAND = 0x112;
int HTCAPTION = 0x02;
int SC_MOVE = 0xF010;
if (message.Msg == WM_SYSCOMMAND && message.WParam.ToInt32() ==
SC_MOVE)
{
return;
}
if (message.Msg == WM_NCLBUTTONDOWN && message.WParam.ToInt32() ==
HTCAPTION)
{
return;
}
base.WndProc(ref message);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace DraggableControls
{
public static class ControlDragExtension
{
private static Dictionary<Control, bool>
controlDraggabilityByControl = new Dictionary<Control, bool>(); // TKey
is
control to drag, TValue is a Boolean
flag used to determine the dragging state.
private static System.Drawing.Size mouseOffset;
/// <summary>
/// Enable/Disable control dragging.
/// </summary>
public static void Draggable(this Control control, bool enable)
{
if (enable) // Enable control drag feature.
{
if (controlDraggabilityByControl.ContainsKey(control))
{
return; // Return if control is already draggable.
}
controlDraggabilityByControl.Add(control, false); // 'false' -
Initial state is 'control not draggable'.
// Assign required event handlers.
control.MouseDown += new MouseEventHandler(Control_MouseDown);
control.MouseUp += new MouseEventHandler(Control_MouseUp);
control.MouseMove += new MouseEventHandler(Control_MouseMove);
}
else // Disable control drag feature.
{
if (!controlDraggabilityByControl.ContainsKey(control))
{
return; // Return if control is not draggable.
}
// Remove event handlers.
control.MouseDown -= Control_MouseDown;
control.MouseUp -= Control_MouseUp;
control.MouseMove -= Control_MouseMove;
controlDraggabilityByControl.Remove(control);
}
}
static void Control_MouseDown(object sender, MouseEventArgs e)
{
mouseOffset = new System.Drawing.Size(e.Location);
controlDraggabilityByControl[(Control)sender] = true; // Turn
control dragging feature on.
}
static void Control_MouseUp(object sender, MouseEventArgs e)
{
controlDraggabilityByControl[(Control)sender] = false; // Turn
control dragging feature off.
}
static void Control_MouseMove(object sender, MouseEventArgs e)
{
if (controlDraggabilityByControl[(Control)sender] == true) // Only
if dragging is turned on.
{
// Calculation of control's new position.
System.Drawing.Point newLocationOffset = e.Location -
mouseOffset;
((Control)sender).Left += newLocationOffset.X;
((Control)sender).Top += newLocationOffset.Y;
}
}
}
}
Even though I have the statements: this.AllowDrop = false; , panel1.AllowDrop = false; and button1.Draggable(false); and also the override void WndProc method that should disable dragging,
the button1 is always draggable.
I changed the event handlers thus:
private void button1_MouseDown(object sender, MouseEventArgs e)
{
if (sender is Button)
{
Button senderButton = (Button)sender;
if (enableDragOperations)
{
if (e.Button == MouseButtons.Left)
{
isDragged = true;
Point ptStartPosition = senderButton.PointToScreen(new Point(e.X, e.Y));
pointOffset = new Point();
pointOffset.X = senderButton.Location.X - ptStartPosition.X;
pointOffset.Y = senderButton.Location.Y - ptStartPosition.Y;
}
else
{
isDragged = false;
}
}
}
}
private void button1_MouseMove(object sender, MouseEventArgs e)
{
if (sender is Button)
{
Button senderButton = (Button)sender;
if (enableDragOperations)
{
if (isDragged)
{
Point newPoint = senderButton.PointToScreen(new Point(e.X, e.Y));
newPoint.Offset(pointOffset);
senderButton.Location = newPoint;
}
}
}
}
private void button1_MouseUp(object sender, MouseEventArgs e)
{
if (sender is Button)
{
Button senderButton = (Button)sender;
if (enableDragOperations)
{
Point newPoint = senderButton.PointToScreen(new Point(e.X, e.Y));
isDragged = false;
}
}
}
I defined a global field: bool enableDragOperations and set it to false.

wpf, how can i get template element on custom-controls, after new instance immediately

questions:
1、i wanna get template elements when calling the constructor, but return null, any way?
2、i found it, get not null obj after loaded event, but i don't want this way.
snippet code:(to see my comments)
using System;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
using System.Windows;
using System.Windows.Input;
namespace WpfPropertyGrid_Demo
{
public class MyButton : Control
{
public static readonly DependencyProperty IsMouseDownProperty;
static MyButton()
{
IsMouseDownProperty = DependencyProperty.Register(
"IsMouseDown",
typeof(bool),
typeof(MyButton),
new FrameworkPropertyMetadata(false)
);
}
public bool IsMouseDown
{
get { return (bool)GetValue(IsMouseDownProperty); }
set { SetValue(IsMouseDownProperty, value); }
}
private BitmapImage _normalImg;
private BitmapImage _overImg;
private BitmapImage _clickImg;
private BitmapImage _disabledImg;
public MyButton()
{
_normalImg = new BitmapImage(new Uri("../../Images/ScrollerBtnBg.png", UriKind.RelativeOrAbsolute));
_overImg = new BitmapImage(new Uri("../../Images/ScrollerThumbnailBtnBg.png", UriKind.RelativeOrAbsolute));
_clickImg = new BitmapImage(new Uri("../../Images/ScrollerThumbnailBg.png", UriKind.RelativeOrAbsolute));
_disabledImg = _clickImg;
var style = new Style(typeof(MyButton));
var controlTemplate = new ControlTemplate();
var gridFactory = new FrameworkElementFactory(typeof(Grid));
var imgFacotry = new FrameworkElementFactory(typeof(Image));
imgFacotry.Name = "Image";
imgFacotry.SetValue(Image.SourceProperty, _normalImg);
gridFactory.AppendChild(imgFacotry);
controlTemplate.VisualTree = gridFactory;
var overTrigger = new Trigger();
overTrigger.Property = UIElement.IsMouseOverProperty;
overTrigger.Value = true;
overTrigger.Setters.Add(new Setter(Image.SourceProperty, _overImg, "Image"));
var disabledTriiger = new Trigger();
disabledTriiger.Property = UIElement.IsEnabledProperty;
disabledTriiger.Value = false;
disabledTriiger.Setters.Add(new Setter(Image.SourceProperty, _disabledImg, "Image"));
var downTrigger = new Trigger();
downTrigger.Property = MyButton.IsMouseDownProperty;
downTrigger.Value = true;
downTrigger.Setters.Add(new Setter(Image.SourceProperty, _clickImg, "Image"));
controlTemplate.Triggers.Add(overTrigger);
controlTemplate.Triggers.Add(disabledTriiger);
controlTemplate.Triggers.Add(downTrigger);
style.Setters.Add(new Setter(Control.TemplateProperty, controlTemplate));
this.PreviewMouseDown += new System.Windows.Input.MouseButtonEventHandler(MyButton_PreviewMouseDown);
this.PreviewMouseUp += new System.Windows.Input.MouseButtonEventHandler(MyButton_PreviewMouseUp);
this.MouseLeave += new System.Windows.Input.MouseEventHandler(MyButton_MouseLeave);
this.MouseEnter += new MouseEventHandler(MyButton_MouseEnter);
Style = style;
// 1、why cann't find "Image" element, it return null obj, i wanna get it immediately, any way?
// 2、return not null after loaded event
// var image = controlTemplate.FindName("Image", this );
this.Loaded += new RoutedEventHandler(MyButton_Loaded);
}
void MyButton_MouseEnter(object sender, MouseEventArgs e)
{
IsMouseDown = e.LeftButton == MouseButtonState.Pressed;
}
void MyButton_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e)
{
IsMouseDown = false;
}
void MyButton_PreviewMouseUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
IsMouseDown = false;
}
void MyButton_PreviewMouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
IsMouseDown = true;
}
void MyButton_Loaded(object sender, RoutedEventArgs e)
{
// return not null after loaded event
var image = this.Template.FindName("Image", this) as Image;
}
}
}
Try Visual Helper Class here I hope this will help

TreeView in Winforms and focus problem

Can anyone please explain to my why the form in the code below gets out of focus when selecting a treenode in the tree? What should happen is that the form/button should get the focus when the tree disappears like the listview example but it doesn't.
Code example:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace FocusTest
{
public partial class Form1 : Form
{
#region Generated
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.Windows.Forms.ListViewItem listViewItem1 = new System.Windows.Forms.ListViewItem("Item1");
System.Windows.Forms.ListViewItem listViewItem2 = new System.Windows.Forms.ListViewItem("Item2");
System.Windows.Forms.ListViewItem listViewItem3 = new System.Windows.Forms.ListViewItem("Item3");
System.Windows.Forms.TreeNode treeNode1 = new System.Windows.Forms.TreeNode("Node0");
System.Windows.Forms.TreeNode treeNode2 = new System.Windows.Forms.TreeNode("Node1");
System.Windows.Forms.TreeNode treeNode3 = new System.Windows.Forms.TreeNode("Node2");
this.button1 = new System.Windows.Forms.Button();
this.listView1 = new System.Windows.Forms.ListView();
this.button2 = new System.Windows.Forms.Button();
this.treeView1 = new System.Windows.Forms.TreeView();
this.SuspendLayout();
//
// button1
//
this.button1.Location = new System.Drawing.Point(12, 12);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 0;
this.button1.Text = "button1";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// listView1
//
this.listView1.Items.AddRange(new System.Windows.Forms.ListViewItem[] {
listViewItem1,
listViewItem2,
listViewItem3
});
this.listView1.Location = new System.Drawing.Point(12, 41);
this.listView1.Name = "listView1";
this.listView1.Size = new System.Drawing.Size(121, 97);
this.listView1.TabIndex = 1;
this.listView1.UseCompatibleStateImageBehavior = false;
this.listView1.Visible = false;
this.listView1.SelectedIndexChanged += new System.EventHandler(this.listView1_SelectedIndexChanged);
this.listView1.View = View.List;
//
// button2
//
this.button2.Location = new System.Drawing.Point(310, 11);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(75, 23);
this.button2.TabIndex = 2;
this.button2.Text = "button2";
this.button2.UseVisualStyleBackColor = true;
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// treeView1
//
this.treeView1.Location = new System.Drawing.Point(310, 41);
this.treeView1.Name = "treeView1";
treeNode1.Name = "Node0";
treeNode1.Text = "Node0";
treeNode2.Name = "Node1";
treeNode2.Text = "Node1";
treeNode3.Name = "Node2";
treeNode3.Text = "Node2";
this.treeView1.Nodes.AddRange(new System.Windows.Forms.TreeNode[] {
treeNode1,
treeNode2,
treeNode3});
this.treeView1.Size = new System.Drawing.Size(121, 97);
this.treeView1.TabIndex = 3;
this.treeView1.Visible = false;
this.treeView1.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.treeView1_AfterSelect);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(760, 409);
this.Controls.Add(this.treeView1);
this.Controls.Add(this.button2);
this.Controls.Add(this.listView1);
this.Controls.Add(this.button1);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Button button1;
private System.Windows.Forms.ListView listView1;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.TreeView treeView1;
#endregion
public Form1()
{
InitializeComponent();
}
#region TreeView
private void button2_Click(object sender, EventArgs e)
{
ToggleTreeView();
}
private void ToggleTreeView()
{
if (treeView1.Visible)
{
Controls.Remove(treeView1);
treeView1.Visible = false;
}
else
{
Controls.Add(treeView1);
treeView1.Size = new Size(300, 400);
treeView1.Location = PointToClient(PointToScreen(new System.Drawing.Point(button2.Location.X, button2.Location.Y + button2.Height)));
this.treeView1.BringToFront();
treeView1.Visible = true;
treeView1.Select();
}
}
private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
ToggleTreeView();
}
#endregion
#region ListView
private void button1_Click(object sender, EventArgs e)
{
ToggleListView();
}
private void ToggleListView()
{
if (listView1.Visible)
{
Controls.Remove(listView1);
listView1.Visible = false;
}
else
{
Controls.Add(listView1);
listView1.Size = new Size(300, 400);
listView1.Location = PointToClient(PointToScreen(new System.Drawing.Point(button1.Location.X, button1.Location.Y + button1.Height)));
this.listView1.BringToFront();
listView1.Visible = true;
listView1.Select();
}
}
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
if (listView1.Visible)
ToggleListView();
}
#endregion
}
}
Here is the problem and the fix.
TreeView re-grabs focus on Ctrl+Click
I can't explain why the form loses focus, but the problem seems to be the Controls.Remove(treeView1); line. If you remove the Controls.Remove and Controls.Add lines, then it seems to behave better.
Is there a reason why you are removing the treeView from the list of control? Just setting the visibility flag to false will cause the treeView to disappear after the user makes their selection.
EDIT:
In response to your comment:
My guess is that after treeView1_AfterSelect is called, the TreeView is setting focus to itself. Which in your code is impossible because you've removed the control from the form.
To test this theory, I added a timer, replaced the code with:
private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
timer1.Enabled = true;
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
ToggleTreeView();
timer1.Stop();
timer1.Enabled = false;
}
Now it works fine. So I'm guessing that the TreeView is calling this.Focus after it has fired the AfterSelect event. (That is just a guess, maybe someone else knows more about the internals them me:) )
And the reason why this is working with the ListView, is that it does not set focus to itself after listView1_SelectedIndexChanged.

Resources