I have ax windows media player in my windows forms application. When the user double clicks on it, it becomes full screen.
PROBLEM: I want the user to be able to go back to normal screen when he presses the "escape key".
I have put a keydown event on the ax media player. This key down event works when in normal mode, but fails when the media player is made full screen.
WMPLarge.KeyDownEvent += new AxWMPLib._WMPOCXEvents_KeyDownEventHandler(Form1_KeyDown);
private void Form1_KeyDown(object sender, AxWMPLib._WMPOCXEvents_KeyDownEvent e)
{
if (e.nKeyCode == 27)
{
MessageBox.Show("");
WMPLarge.fullScreen = false;
WMPSmall.fullScreen = false;
}
}
How can I achieve this ?
Here is one code snippet I used, I hope that helps.
public partial class Form16 : Form,IMessageFilter
{
public Form16()
{
InitializeComponent();
}
private void Form16_Load(object sender, EventArgs e)
{
this.axWindowsMediaPlayer1.URL = #"D:\MyVideo\myfile.wmv";
Application.AddMessageFilter(this);
}
private void Form16_FormClosing(object sender, FormClosingEventArgs e)
{
Application.RemoveMessageFilter(this);
}
#region IMessageFilter Members
private const UInt32 WM_KEYDOWN = 0x0100;
public bool PreFilterMessage(ref Message m)
{
if (m.Msg == WM_KEYDOWN)
{
Keys keyCode = (Keys)(int)m.WParam & Keys.KeyCode;
if (keyCode == Keys.Escape)
{
this.axWindowsMediaPlayer1.fullScreen = false;
}
return true;
}
return false;
}
#endregion
}
Related
im using visual studio to make a screen recorder using the ScreenRecorderLib library (but it is not related to my question) and c#. It is my first app ever even though i made some games in unity using c#.
I want to, on record button click or keyboard shortcut (for example crtl+a), to minimize the window in taskbar. I managed to do this using
private void RecordButton_Click(object sender, EventArgs e)
{
ActiveControl = null;
try
{
if (_IsRecording)
{
//some actions to stop recording (not interresting for my question)
WindowState = FormWindowState.Normal;
}
UpdateProgress();
if (_rec == null)
{
// some actions to make settings active and launch the recording
WindowState = FormWindowState.Minimized;
}
}}
and my code for the shortcuts
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control && e.KeyCode.ToString() == "A")
{
RecordButton.PerformClick();
}
}
This is not my real code but i tried to select some interresting parts for my question.
I manage to minimize my button in taskbar with shortcut or with button, but not to stop the recording using the shortcut while it is minimized. I would like that while recording and window minimised to be able to click crtl+a to stop the recording
Any ideas???
"How to use shortcut keys when the application is inactive" has been collected in API: MouseKeyHook.
You only need to modify the operations you need in the appropriate places.
globalmousekeyhook
Sample:
nuget install MouseKeyHook
public bool Flag { get; set; }
private void MinOrNarmal() {
//1. Define key combinations
var undo = Combination.TriggeredBy(Keys.A).With(Keys.Control);
//2. Define actions
Action actionUndo = DoSomething;
void DoSomething() {
if (Flag == false) {
this.WindowState = FormWindowState.Minimized;
Flag = true;
return;
}
if (Flag == true) {
this.WindowState = FormWindowState.Normal;
Flag = false;
}
}
//3. Assign actions to key combinations
var assignment = new Dictionary<Combination, Action> { { undo, actionUndo } };
//4. Install listener
Hook.GlobalEvents().OnCombination(assignment);
}
private void Form1_Load(object sender, EventArgs e) {
MinOrNarmal();
}
Press "Control+A":
You can also write global hotkeys yourself.
Only realize the function of shrinking the window:
private void Form1_Load(object sender, EventArgs e) {
this.KeyPreview = true;
}
private void Form1_KeyDown(object sender, KeyEventArgs e) {
if (e.Control && e.KeyCode == Keys.A) {
this.WindowState = FormWindowState.Minimized;
}
}
https://www.fluxbytes.com/csharp/how-to-register-a-global-hotkey-for-your-application-in-c/#comments
This perfectly answers my question. I will put a code down below for the people who want to have more than one shortcut. I'm a beginner, so mabe my explanations are not correct, but i tried to explain them in the esasiest way and in the way i understood them
public partial class Form1 : Form
{
[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern bool RegisterHotKey(IntPtr hWnd, int id1, int fsModifiers, int vk);
//for creating another hotKey
[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern bool RegisterHotKey1(IntPtr hWnd, int id2, int fsModifiers, int vk);
//here you can create even more shortcuts
[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern bool UnregisterHotKey(IntPtr hWnd, int id1);
[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern bool UnregisterHotKey1(IntPtr hWnd, int id2);
//remember unreg them
enum KeyModifier
{
None = 0,
Alt = 1,
Control = 2,
Shift = 4,
WinKey = 8
}
public Form1()
{
InitializeComponent();
int id1 = 0; // The id of the hotkey.
RegisterHotKey(this.Handle, id1, (int)KeyModifier.Shift, Keys.F1.GetHashCode());
int id2 = 1; // The 2nd id of the hotkey.
RegisterHotKey(this.Handle, id2, (int)KeyModifier.Shift, Keys.F2.GetHashCode());// Register Shift + A as global hotkey.
}
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
if (m.Msg == 0x0312)
{
if (m.WParam.ToInt32() == 0)
{
RecordButton.PerformClick();
}
if(m.WParam.ToInt32() == 1)
{
PauseButton.PerformClick();
}
//add the other shortcuts just replace == 1 by the id value
}
}
private void ExampleForm_FormClosing(object sender, FormClosingEventArgs e)
{
UnregisterHotKey(this.Handle, 0); // Unregister hotkey with id 0 before closing the form. You might want to call this more than once with different id values if you are planning to register more than one hotkey.
UnregisterHotKey(this.Handle, 1);
}
//delete them with the id
I am new to windows app development. I am developing a Windows Form Application where the layout is as follows:
There is one textbox and i have created the keyboard inside the application using SendKeys event.
Problem is that all other application on the system are able to detect the keys but the textbox inside the application is not able to detect the keys.
Basically app is having complete keyboard this is just one button press code
What I have tried:
public partial class Form1 : Form
{
Control focusedC;
protected override CreateParams CreateParams
{
get
{
CreateParams param = base.CreateParams;
param.ExStyle |= 0x08000000;
return param;
}
}
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
FormBorderStyle = FormBorderStyle.None;
WindowState = FormWindowState.Maximized;
TopMost = true;
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Escape) {
FormBorderStyle = FormBorderStyle.Sizable;
WindowState = FormWindowState.Normal;
TopMost = false;
}
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
//checkbox is for CapsLock Key
}
private void button14_Click(object sender, EventArgs e)
{
if (checkBox1.Checked && focusedC != null)
{
focusedC.Focus();
SendKeys.Send("Q");
}
else if(focusedC != null)
{
focusedC.Focus();
SendKeys.Send("q");
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
focusedC = sender as TextBox;
}
}
Of cource it doesn't work on your window. You set the WS_EX_NOACTIVATE style! It works on other windows but not yours, obviously. If you want it to work on your textbox remove or comment this line
param.ExStyle |= 0x08000000;
and it will work fine in your app window not others:
private void button14_Click(object sender, EventArgs e)
{
if (checkBox1.Checked)
{
textBox1.Focus();
SendKeys.Send("Q");
}
else
{
textBox1.Focus();
SendKeys.Send("q");
}
}
For WPF applications, you have to use SendKeys.SendWait() method.
SendKeys.SendWait("Q")
SendKeys.Send() will work for WinForm Applications.
Another option is to use WinAPI instead of SendKeys. More information here
Edit 1
Control focusedC;
//Enter event handler for your TextBox
private void textBox1_TextChanged(object sender, EventArgs e)
{
focusedC = sender as TextBox;
}
//Click event handler
private void button14_Click(object sender, EventArgs e)
{
if (focusedC != null)
{
focusedC.Focus();
SendKeys.Send("Q");
}
}
Edit 2: Using WinAPI
[DllImport("user32.dll")]
static extern void SendInput(byte bVk, byte bScan, uint dwFlags, int dwExtraInfo);
public static void PressKey(byte keyCode)
{
const int KEYEVENTF_EXTENDEDKEY = 0x1;
const int KEYEVENTF_KEYUP = 0x2;
SendInput((byte)keyCode, 0x45, KEYEVENTF_EXTENDEDKEY, 0);
SendInput((byte)keyCode, 0x45, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
}
Use by calling the PressKey function and Keycodes can be found here
This question already has answers here:
how not to allow multiple keystokes received at one key press?
(3 answers)
Closed 6 years ago.
In a Windows forms application I'm trying to execute some function when I press a hotkey using Form's KeyDown event. The problem is that when I keep the hotkey pressed the event fires continuously.
I just want to execute some function at the first time I press the button and another function when I release it.
Here is the code I used to accomplish this operation:
bool isPressed_Num7 = false;
bool isPressed_Num9 = false;
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData == Keys.NumPad7 && !isPressed_Num7)
{
isPressed_Num7 = true;
Console.WriteLine("Keydown 7");
}
if (e.KeyData == Keys.NumPad9 && isPressed_Num9)
{
isPressed_Num9 = true;
Console.WriteLine("Keydown 9");
}
}
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyData == Keys.NumPad7)
{
isPressed_Num7 = false;
Console.WriteLine("Keyup 7");
}
if (e.KeyData == Keys.NumPad9)
{
isPressed_Num9 = false;
Console.WriteLine("Keyup 9");
}
}
I'm going to use a bunch of hotkeys. So what I'm asking is there a better way to accomplish what I'm trying to do?
You could just a dictionary instead of one variable per key.
Dictionary<Keys, bool> keysPressed = new Dictionary<Keys, bool>();
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
keysPressed[e.KeyData] = false;
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (!keysPressed.ContainsKey(e.KeyData) || !keysPressed[e.KeyData]) {
Console.WriteLine(e.KeyData);
keysPressed[e.KeyData] = true;
}
}
Try this:
bool isPressed_Num7 = false;
bool isPressed_Num9 = false;
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if ((e.KeyData == Keys.NumPad7) && (!isPressed_Num7))
{
isPressed_Num7 = true;
Console.WriteLine("Keydown 7");
}
if ((e.KeyData == Keys.NumPad9) && (!isPressed_Num9))
{
isPressed_Num9 = true;
Console.WriteLine("Keydown 9");
}
}
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
if ((e.KeyData == Keys.NumPad7)&&(isPressed_Num7==true))
{
isPressed_Num7 = false;
Console.WriteLine("Keyup 7");
}
if ((e.KeyData == Keys.NumPad9)&&(isPressed_Num9==true))
{
isPressed_Num9 = false;
Console.WriteLine("Keyup 9");
}
}
This solution uses the recommended way to handle keyboard shortcuts according to Microsoft. And allows you to assign action to invoke when pressing a key combination.
public partial class Form1 : Form
{
private readonly IDictionary<Keys, Action> _operationsMap = new Dictionary<Keys, Action>();
public Form1()
{
InitializeComponent();
RegisterKeyShortcuts();
}
private void RegisterKeyShortcuts()
{
_operationsMap.Add(Keys.Control | Keys.F, WhenPressingF);
}
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (_operationsMap.ContainsKey(keyData))
{
_operationsMap[keyData].Invoke();
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
protected void WhenPressingF()
{
MessageBox.Show("What the Ctrl+F?");
}
}
I've been using the MouseKeyHook NuGet package for a project where a single key press needs to be monitored to provide explicit functionality. The prototype application I have written, checks the required key is pressed and then sets the Handled property to true. The key I'm testing with is LaunchApplication2, now the problem I'm having is the key press isn't always surpressed, at the moment if Microsoft Word or Excel is in focus then the calculator launches!
The code is as follows:
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private IKeyboardMouseEvents keyboardHookListener;
private SolidColorBrush inactiveBrush = new SolidColorBrush(Colors.White);
private SolidColorBrush activeBrush = new SolidColorBrush(Colors.LightGreen);
private bool pressed = false;
public MainWindow()
{
InitializeComponent();
this.Background = inactiveBrush;
this.keyboardHookListener = Hook.GlobalEvents();
this.keyboardHookListener.KeyDown += keyboardHookListener_KeyDown;
this.keyboardHookListener.KeyUp += keyboardHookListener_KeyUp;
}
void keyboardHookListener_KeyUp(object sender, System.Windows.Forms.KeyEventArgs e)
{
if (e.KeyData == System.Windows.Forms.Keys.LaunchApplication2)
{
if (pressed)
{
this.Background = inactiveBrush;
this.displayLabel.Content = string.Empty;
this.pressed = false;
System.Diagnostics.Debug.WriteLine("*********Finished*********");
}
}
}
void keyboardHookListener_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
// Filter to specific buttons using the KeyData property of the event arguments.
if (e.KeyData == System.Windows.Forms.Keys.LaunchApplication2)
{
e.Handled = true;
e.SuppressKeyPress = true;
// Use a flag to stop code executing multiple times as whilst a key is pressed the KeyDown keeps firing.
if (!pressed)
{
System.Diagnostics.Debug.WriteLine("*********Started*********");
this.pressed = true;
this.Background = activeBrush;
this.displayLabel.Content = e.KeyData.ToString();
}
}
}
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
this.keyboardHookListener.KeyDown -= this.keyboardHookListener_KeyDown;
this.keyboardHookListener.KeyUp -= this.keyboardHookListener_KeyUp;
this.keyboardHookListener.Dispose();
}
}
I've tried using the SuppressKeyPress property as well but that doesn't have any effect. Any explanations or proposals to fix it would be great!
I have a main form window which will pop up a new form window. I want to lock the location of the popup form so that the window cannot be moved and it will move at the same time as the main form.
(so if a user drags the main form the popup moves with it)
Did a search on the site and some did it like this:
this.FormBorderStyle=System.Windows.Forms.FormBorderStyle.None
and I have the Locked attribute set to True but that doesn't work.
But I want to keep the borders. What's the proper way of locking a form?
public class Form1
{
private Form2 Form2 = new Form2();
private Point form2Location;
private Point form1Location;
private void Button1_Click(System.Object sender, System.EventArgs e)
{
form1Location = this.Location;
Form2.Show();
form2Location = Form2.Location;
}
private void Form1_Move(System.Object sender, System.EventArgs e)
{
Form2.IsMoving = true;
Point form2OffSetLocation = new Point(this.Location.X - form2Location.X, this.Location.Y - form2Location.Y);
Form2.Location = form2OffSetLocation;
Form2.IsMoving = false;
}
}
public class Form2
{
public bool IsMoving;
private void Form2_Move(System.Object sender, System.EventArgs e)
{
if (IsMoving) return;
if (staticLocation.X != 0 & staticLocation.Y != 0) this.Location = staticLocation;
}
private Point staticLocation;
private void Form2_Load(System.Object sender, System.EventArgs e)
{
staticLocation = this.Location;
}
}
I agree with Hans on this one and I think once you see how dodgy it looks you'll probably agree too.
You could do something like this (taken from here):
protected override void WndProc(ref Message message)
{
const int WM_SYSCOMMAND = 0x0112;
const int SC_MOVE = 0xF010;
switch(message.Msg)
{
case WM_SYSCOMMAND:
int command = message.WParam.ToInt32() & 0xfff0;
if (command == SC_MOVE)
return;
break;
}
base.WndProc(ref message);
}