How can i fix this Esc Key error? - c#

I have this chunk of code in my Notepad clone program, it is to track my carat location in my RichTextBox and has been working fine for me.
private void richTextBox1_KeyDown(object sender, KeyEventArgs e)
{
Curpos();
}
private static int EM_LINEINDEX = 0xbb;
[DllImport("user32.dll")]
extern static int SendMessage(IntPtr hwnd, int message, int wparam, int lparam);
private void Curpos()
{
{
int line, col, index;
index = richTextBox1.SelectionStart;
line = richTextBox1.GetLineFromCharIndex(index);
col = index - SendMessage(richTextBox1.Handle, EM_LINEINDEX, -1, 0);
Lblcurpos.Text = "Line: " + (++line).ToString() + ", Column:" + (++col).ToString();
}
}
It has been working perfectly for me, until i added some code so that i could close my program with the Esc Key.
Here is the code for my Esc Key:
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Escape)
{
this.Close();
}
}
EDIT: This is where it has the problem:
index = richTextBox1.SelectionStart;
When i am doing this, i can run my program fine, type text in my RichTextBox and everything but when i press the Esc Key it says:
Cannot Access disposed object
Object name: 'RichTextBox'
Then is says:
Trouble Shooting Tips:
Make sure you have not released a resource before attempting to use this.
Get general help for this exception
Any ideas on what i can do? I tried to use the shortcut keys but it doesn't have a Esc key you can use for the shortcut. Any help with either doing a different shortcut or a fix to this problem, i would like it!!

Try:
Application.Exit();
instead of
this.Close();
From MSDN:
Application.Exit
Informs all message pumps that they must terminate, and then closes all application windows after the messages have been processed. This is the code to use if you are have called Application.Run (WinForms applications), this method stops all running message loops on all threads and closes all windows of the application.

Do note that Application.Exit() is not a substitute for this.Close(). Exit() terminates the entire application, Close() just close the form.
There are better ways to avoid accidents like this. When you handle shortcut keystrokes like you did, you should always set e.Handled and e.SuppressKeyPress to true so the keystroke will be completely dismissed and not generate any additional events. Like the one that bombed your code.
By far the best way is to use the dedicated method for this in Winforms, ProcessCmdKey(). It implements true shortcut keystroke behavior, the KeyPreview property is a VB6 compatibility feature which is close but not equivalent. Make it look like this:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
if (keyData == Keys.Escape) {
this.Close();
return true; // Used, don't process any further
}
return base.ProcessCmdKey(ref msg, keyData);
}

Related

How to Disable Shortkeys on ComboBox In C# using Windows Application?

In Main Form i have Short Cut Keys(ctrl + S ) for saving the data in DataBase. For combobox (ctrl + Alphabets) is the default Operation. How can I disable shortcut keys for Combobox?
UPDATE:
On keyPress event we can Do this
if (ModifierKeys == Keys.Control)
{
e.Handled = true;
}
You can try overriding ProcessCmdKey method of the Main Form:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
const int WM_KEYDOWN = 0x100;
if (keyData == (Keys.Control | Keys.S)) {
if (msg.Msg == WM_KEYDOWN)
MySaveDataToDatabase(); // <- Do your save command
return true; // <- Stop processing the WM_KeyDown message for Ctrl + S (and shortcut as well)
}
// All other key messages process as usual
return base.ProcessCmdKey(ref msg, keyData);
}
I get the feeling that your problem is actually that the combobox is getting keypresses before your form. Be sure to set the Form's KeyPreview property to true if you want to handle keypresses before your controls.
More information about the KeyPreview property:
http://msdn.microsoft.com/en-us/library/system.windows.forms.form.keypreview(v=vs.100).aspx
If you are getting issues like overriding the F4 key (which in a combobox shows all options available by default), note the bit about setting the KeyPressEventArgs.Handled property in the form's KeyPress event handler to true.
For most hot keys you can override the PreviewKeyDown event specify what to allow or not, eg:
void comboBox_PreviewKeyDown(object sender, KeyEventArgs e)
{
var keysToIgnore = new []{
Keys.S,
Keys.X,
Keys.F4,
Keys.Space,
}.ToList();
if (keysToIgnore.Contains(e.KeyCode)) {
if(e.Modifiers == Keys.Alt) ; // Do stuff (or don't) here
}
}
There's all sorts of ways you can structure your logic depending on what your actual use case is but hopefully you get the idea.
You might find some hot key combinations aren't possible to disable this way, in which case you'll need to use the Win32API: UnregisterHotKey. More info here:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms646327%28v=vs.85%29.aspx
The main advantage of using the PreviewKeyDown event is you can also easily replace behaviour instead of just disabling it. The main advantage of using UnregisterHotKey is it operates at a lower level and is a far more robust and reliable way of disabling hot keys.
EDIT:
If you need to get a contiguous range of values you can try something like:
int keyCode = (int) (e.KeyCode);
if(keyCode >= (int)(Keys.A) && keyCode <= (int)(Keys.Z)) { /* do stuff */ }
but again, an ideal solution really depends on the specifics of your use case. There's no generic 'right answer'.

Stopping keys from repeating (C#)

In this application, I need to be able to stop the response from a key which is held down in order to prevent unnessecary data from entering the output. The problem I'm having is, using the methods in my code below does prevent the keys from repeating, but it also stops them from being responsive enough - as the users are hitting the keys very quickly.
I'm not sure if it's my hardware, api restriction or a problem with my code, but the routines I have below do not simply come round fast enough to work without making the program impossible to use. A way of identifying if a key is being actively held down (and for how long) would also help another feature for the program and solve this current issue.
Any ideas?
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
e.SuppressKeyPress = isKeyDown;
isKeyDown = true;
}
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
isKeyDown = false;
}
private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!isStreamPlaying) return;
if (e.KeyChar.Equals('d') || e.KeyChar.Equals('j'))
{
//red hit
SoundPlayer hitSounds = new SoundPlayer(taikoLiveMapper.Properties.Resources.normal_hitnormal);
hitSounds.Play();
outputlist.Add(string.Format("320,240,{0},1,{1}", ms, 0));
lastms = ms;
}
else if (e.KeyChar.Equals('s') || e.KeyChar.Equals('k'))
{
//blue hit
SoundPlayer hitSounds = new SoundPlayer(taikoLiveMapper.Properties.Resources.normal_hitclap);
hitSounds.Play();
outputlist.Add(string.Format("320,240,{0},1,{1}", ms, 8));
lastms = ms;
}
}
You can use GetKeyState to find out if a key is down and use that to track the keys:
[DllImport("user32.dll")]
static extern short GetKeyState(int key);
static bool IsKeyPressed(Keys key)
{
short state = GetKeyState((int)key);
return ((state & 128) != 0);
}
int i = 0;
Dictionary<Keys, DateTime> downSince = new Dictionary<Keys, DateTime>();
private void UpdateKeyStates()
{
foreach (var entry in downSince.ToArray())
{
if (!IsKeyPressed(entry.Key))
downSince.Remove(entry.Key);
}
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
UpdateKeyStates();
if (!downSince.ContainsKey(e.KeyCode))
{
downSince.Add(e.KeyCode, DateTime.UtcNow);
i++;
}
Text = i.ToString() + " " +(int)(DateTime.UtcNow - downSince[e.KeyCode]).TotalMilliseconds;
}
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
UpdateKeyStates();
}
This example counts i up every time a key is pressed, and shows for how long it has been pressed. It uses GetKeyState instead of tracking KeyDown/KeyUp since you might miss those messages if something else has focus.
According to the documentation, "[d]uplicate KeyDown events occur each time the key repeats, if the key is held down, but only one KeyUp event is generated when the user releases the key."
So the simplest solution is to ignore a repeated KeyDown event unless its corresponding KeyUp event has been seen.
Just worked for me.
Use Timers instead: initialize timers, one for each "action" (e.g. pressing d/j or s/k) move the red hit/blue hit code inside the timer and instead of your current code, have this:
if (e.KeyChar.Equals('d') || e.KeyChar.Equals('j'))
{
//red hit
if (!tmrRedHit.Enabled)
tmrRedHit.Enabled = true;
}
else if (e.KeyChar.Equals('s') || e.KeyChar.Equals('k'))
{
//blue hit
if (!tmrBlueHit.Enabled)
tmrBlueHit.Enabled = true;
}
And in the timers Elpased event also set their Enabled to false after the code is executed.

Multiple key presses doing different events in C#

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.W)
player1.moveUp();
if (e.KeyCode == Keys.NumPad8)
player2.moveUp();
}
In the above code the moveUp methods basically just increment a value. I want it so both keys can be pressed (or held down)at the same time and both events will trigger.
Thanks,
Nevik
Get the state of the keyboard and check for the status of the keys that you want.
Events are not the best way to go in gaming. You need faster response.
[DllImport("user32.dll")]
public static extern int GetKeyboardState(byte [] lpKeyState);
...
byte[] bCharData = new byte[256];
GetKeyboardState(bCharData);
Another way, taken from here,
[DllImport("user32.dll")]
static extern short GetKeyState(VirtualKeyStates nVirtKey);
...
public static bool IsKeyPressed(VirtualKeyStates testKey)
{
bool keyPressed = false;
short result= GetKeyState(testKey);
switch (result)
{
case 0:
// Not pressed and not toggled on.
keyPressed = false;
break;
case 1:
// Not pressed, but toggled on
keyPressed = false;
break;
default:
// Pressed (and may be toggled on)
keyPressed = true;
break;
}
return keyPressed;
}
More links.
Basically, these are already available on net. Try searching before asking. It will be faster :)
Let's assume you have a "game loop" that updates the object you're moving with the keyboard. The KeyDown event should change the object state to "moving upwards". And your loop then gives it new positions each time it runs.
The KeyUp event should change the state back to "idle". Iff the state is still "moving upwards".
You now no longer depend on a keystroke repeating to keep the object moving. And will have no trouble with the player pressing multiple keys at the same time.

Why does my loop use 100% CPU and never end?

I have this method:
private delegate void watcherReader(StreamReader sr);
private void watchProc(StreamReader sr) {
while (true) {
string line = sr.ReadLine();
while (line != null) {
if (stop) {
return;
}
//Console.WriteLine(line);
line = stripColors(line);
txtOut.Text += line + "\n";
line = sr.ReadLine();
}
}
}
And it reads the streams from a Process (cmd.exe). When the user closes the cmd.exe window, it causes the CPU usage to jump to 100%. When playing with the debugger I see that it stops on the sr.ReadLine() and never returns. Because this is watching both the StandardErrorStream and the StandardOutputStream it uses 100% on both cores.
Here's some more code of the project if you need it.
[DllImport("User32")]
private static extern int ShowWindow(int hwnd, int nCmdShow); //this will allow me to hide a window
public ConsoleForm(Process p) {
this.p = p;
p.Start();
ShowWindow((int)p.MainWindowHandle, 0); //0 means to hide the window.
this.inStream = p.StandardInput;
this.outStream = p.StandardOutput;
this.errorStream = p.StandardError;
InitializeComponent();
wr = new watcherReader(watchProc);
wr.BeginInvoke(this.outStream, null, null);
wr.BeginInvoke(this.errorStream, null, null);
}
public void start(string[] folders, string serverPath) {
this.inStream.WriteLine("chdir C:\\cygwin\\bin");
this.inStream.WriteLine("bash --login -i");
this.inStream.WriteLine("");
}
//code example from http://geekswithblogs.net/Waynerds/archive/2006/01/29/67506.aspx it is
//to make the textbox autoscroll I don't understand what it does, but it works.
#region autoscroll
[DllImport("User32.dll", CharSet = CharSet.Auto, EntryPoint = "SendMessage")]
static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
const int WM_VSCROLL = 277;
const int SB_BOTTOM = 7;
private void txtOut_TextChanged(object sender, EventArgs e) {
IntPtr ptrWparam = new IntPtr(SB_BOTTOM);
IntPtr ptrLparam = new IntPtr(0);
SendMessage(((RichTextBox)sender).Handle, WM_VSCROLL, ptrWparam, ptrLparam);
}
#endregion
private void ConsoleForm_FormClosed(object sender, FormClosedEventArgs e) {
this.stop = true;
try {
this.p.Kill();
} catch (InvalidOperationException) {
return;
}
}
Another interesting this is that it doesn't always hide the cmd window like it's supposed to. It hides it the first time, and then the second (or after) it won't hide it. This is when the user can close the cmd.exe window and cause the readline to act funny. It also never reads the last line outputted to cmd unless it exits.
Any suggestions on how to fix this?
I would change:
while(true)
to:
while(!sr.EOS) {
}
It is a better way to check to end the loop.
Whenever you have a while(true) loop in your code you're going to peg your cpu (or at least one core) at 100%, unless you also have a way to break out of the loop. In your case, you do have a return statement, but at no point in the loop do you ever do anything to the stop variable guarding it.
This seems like an interesting issue here. At first glance, it would appear that ReadLine has an issue with the handle being closed from under it while it's trying to read data, and thus would seem to be a bug in the Framework. However, I'm not convinced that easily that it's a bug in the .Net framework...
However, there are a couple low level issues here.
The other answers you have got so far all suggest you modify the while loop. I would do this as well, but I don't think this is the root of your problem. You do not need a sleep in there, because you will get your waitstate from the ReadLine(), unless there is no data to read, and it just returns a failue, THEN you will 'tight-loop'. So, make sure you are checking any and all error states during this loop.
If you do not, I can see issues.
If everything else is working as it should, then if I were you, I would start by trying to identify if you can duplicate it outside of your program with a small demo program. I'm sure there is plenty of error checking in the Framework's Stream handling. However, it looks like you are running some stuff from Cygwin, and that's the output you are reading from the cmd shell.
Try making a simple app that just spits out data to stdout, and stderr, and then make sure the app closes while you are still reading..
Also use the debugger to see what line== after the failure occurs.
Larry
Having while(true) with no sleep in the loop will cause 100% CPU usage.
You need to sleep for some amount of time or break out of the loop at some point so the CPU can do something else.
At the very least you should be doing something along the lines of:
while (sr.Peek() >= 0)
{
Console.WriteLine(sr.ReadLine());
Thread.Sleep(0);
}

Richtextbox.invoke, C#, Form Still hanging

I've written a c# application to run an external program and i've redirectet it's output to a richtextbox in my form. I've created the process using the following settings
p1.StartInfo.RedirectStandardOutput = true;
p1.OutputDataReceived += new DataReceivedEventHandler(outputreceived);
and in the outputreceived event
void outputreceived(object sender, DataReceivedEventArgs e)
{
if (!string.IsNullOrEmpty(e.Data))
{
richTextBox1.Invoke(new UpdateOutputCallback(this.updateoutput),
new object[] { e.Data });
}
}
void updateoutput(string text)
{
int len = text.Length;
int start = richTextBox1.Text.Length;
richTextBox1.Text += text + Environment.NewLine;
richTextBox1.Select(start, len);
richTextBox1.SelectionColor = System.Drawing.Color.White;
richTextBox1.Select(richTextBox1.Text.Length, 0);
richTextBox1.ScrollToCaret();
}
Now the thing is though it is working, but my main form which contains the textbox, hangs if the output is huge from the application. I think each time the invoke call leads to repainting of the form, which happens very frequently. Is there any alternative so that i can see the updates to the textbox as they happen and also keep the form completely active?
Update:
I think I got my answer, I used BeginInvoke when I should have used Invoke.
Update 1:
I tried both BeginInvoke and Suspendlayout but it is not giving me the desired functionality, what happens is that the process has returened all the standardoutput to the string, but the thread which is responsible for updating the text is taking it's own time to print the data. Can i do any thing to it?
Since you've already solved your problem, I'll just note that it will be faster if you use rtb.AppendText (instead of Text += ...) and use pinvoke to scroll to the bottom:
private const int WM_VSCROLL = 0x115;
private const int SB_BOTTOM = 7;
[DllImport("user32.dll", CharSet=CharSet.Auto)]
private static extern int SendMessage(IntPtr hWnd, int wMsg, IntPtr wParam,
IntPtr lParam);
// ...
// Scroll to the bottom, but don't move the caret position.
SendMessage(rtb.Handle, WM_VSCROLL, (IntPtr) SB_BOTTOM, IntPtr.Zero);
You might want to try
richTextBox1.BeginInvoke()
rather than
richTextBox1.Invoke()
That will at least make the call Asynchronous. Still not sure if that will cause the UI thread to lock while the updates are being painted.
Try to suspend and resume layout of richTextBox1
void updateoutput(string text)
{
try
{
richTextBox1.SuspendLayout();
int len = text.Length;
int start = richTextBox1.Text.Length;
richTextBox1.Text += text + Environment.NewLine;
richTextBox1.Select(start, len);
richTextBox1.SelectionColor = Color.White;
richTextBox1.Select(richTextBox1.Text.Length, 0);
richTextBox1.ScrollToCaret();
}
finally
{
richTextBox1.ResumeLayout();
}
}
Is there any alternative so that i can see the updates to the textbox as they happen and also keep the form completely active?
I think you should use Debug.Print to view what's going on instead.
It is an old post, but maybe somebody still looking for it like I did.
You also can do, like "for(writeToTextbox % 10 == 0)" then invoke.
In this case it will be updated only every 10 times.
UPDATE: sorry for the misspelling! (wirte -> write) and thanks for "HaveNoDisplayName" to show it to me!

Categories

Resources