Implementing keyboard short cut using "Keyboard.IsKey..." rescales the window, WHY? - c#

Windows 10.0.18362,
Visual Studio 16.4.5,
.NET 4.8.03752
Hi there
I wanted to setup a keyboard short cut to do something. So I set up the following code:
private void MainWindow_KeyDown(object sender, KeyEventArgs e)
{
if (Keyboard.IsKeyDown(Key.D))
{
// do something
}
}
Basically it works. The only (very nasty) thing that happens is that as soon as I implement "Keyboard.IsKey...(...)" into the code, run it, then pressing any key makes the window scales down (to
about 80%) totally out of nowhere.
I can replace the condition with "true" and it just runs as expected without any random out of nowhere scaling.
Did any one out there experience something similar? This behaviour does absolutely not make any sense, so searching for solutions obviously leads in dead ends only.
Thanks for any help or recommendation.

Related

Automated 'PrtScn' keystroke acts like 'Alt+PrtScrn'

We need a screenshot of our app for a unit test. CaptureScreen() and CopyFromScreen() somehow ignore the app and return pictures of an empty desktop. So we wrote this to fake a PrtScn keystroke:
public static Bitmap GetAltScreenshot()
{
Clipboard.Clear();
SendKeys.SendWait("{PRTSC}");
while (!Clipboard.ContainsImage())
{
Thread.Sleep(500);
}
return new Bitmap(Clipboard.GetImage());
}
Alt isn't part of the keystroke, so this should return a bitmap of the entire screen. Yet somehow this snippet returns just the focused window. Which is fine, that solves our problem - but we don't understand how.
Why does this return a shot of just the focused window, instead of the entire monitor?
There is in fact a "reason", turn to the MSDN Library article that documents the key abbreviations you can use. Note the entry for PRINT SCREEN:
{PRTSC} (reserved for future use)
The is a somewhat clumsy way of saying "We know it doesn't work, maybe will fix that some day". That day hasn't yet arrived. So you are probably testing the failure mode of this key and actually like the way it works. This is of course not healthy, they may actually fix the problem some day and break your program.
Do note the Note about the <appSettings> entry that you can add to your .config file, further down that same MSDN page. I suspect, but do not know for a fact, that the SendInput method is more reliable.

Threading in C# with XNA KeyboadInput

I am a bit new to threading (not new to C#, just haven't done much threading). Can someone explain to me why this does not work?
I have a thread which calls a method I will call "Loop". Loop contains a while loop which will continuously run, and on every loop of the while I want it to check if the A Key is down (using Microsoft's Keyboard class within the XNA Framework). But for some reason it never registers that anything is being pressed.
static Thread thread = new Thread(Loop);
static bool abort = false;
public static void Begin()
{
thread.Start();
}
private static void Loop()
{
while (!abort)
{
if (Keyboard.GetState().IsKeyDown(Keys.A))
Console.WriteLine("A pressed.");
}
}
Might anyone know why the Console.WriteLine() is never being called?
EDIT:
I guess I should explain a little bit. What I am actually trying to do is create something similar to ActionScript's events in C#. So I want to pass a "condition" and an "action" to call if that condition is met in this separate class which contains this thread. What this would do would allow me to just add "event listeners" to objects and it would automatically constantly check if one of the events gets triggered, rather than leave it to me to write If statements in code to check for the events.
Upon trying to do so, the first thing I tested was regarding this XNA Keyboard stuff, because it was one of the reasons I originally wanted to build this system, but it didn't work. So I created the standalone code which i posted above to see if I had made an error in my previous code and it still didn't work.
I never use XNA so I didn't really "know" but I've run into similar situations where you can't get keyboard (and other) input from a worker thread. I googled and found that in XNA this does seem to be the case. See this for example
So you need to (and probably want to) process your game input in the GUI thread. Just checking for input on each update tick should be fine. I doubt even if it did work, you would gain any performance - and you might introduce some interesting synchronization bugs ;-)
It does look like your creating your worker thread properly - this just isn't an application for it.

Strange behavior coming from a P/Invoke function - Magic loop

My C# program has a very strange behavior. I'm using four ''hacky'' pinvoke methods in this program: GlobalKeyHooking, HotKey Registering, SetForegroundWindow/GetForegroundWindow, and SendKeys.Send/SendWait.
Here is where there is a behavior I don't understand. I'm stealing the Ctrl+V in a program where the standard cut/copy&paste routine is replaced by an autocomplete list in a listbox that appears and disappears. On some computer with Windows 7, my programs works like a charm, on an other 50% of computers with Windows 7 (and sadly no VS2010 to debug it), a very weird loop appears ---inside--- a method. Since the Ctrl and the V themselves are hooked, I already prevented the method to be infinitely triggered. That's ok. But another loop appears inside the method.
Briefly: myDebugValue increases until it reaches 23-24-25! So something is trying to execute a function a lot of times before deciding to stop.
Does anyone has already seen a similar undesired loop? Even though there is no try/catch block, it's bouncing inside the function.
Can some P/Invokes function crash on some Windows 7 and not on other?
Are P/Invokes having their own invisible low-level assembler error handlers try/catch, stronger than my C# program execution?
Visually, when it's doing it, I see my program UI quickly flashing a lot of times, 25 times, I guess.
private bool getOutOfHere = false;
private int myDebugValue = 0;
private void globalKeyHooking_KeyUp(object sender, KeyEventArgs e)
{
if (getOutOfHere) return;
myDebugValue = 0;
if (e.KeyCode == Keys.LControlKey)
{
getOutOfHere = true;
SendKeys.SendWait("^v");
getOutOfHere = false;
myDebugValue++;
}
}
I tried to compile with 2.0, 3.0 and 4.0, and on the same 4 computers, in all cases, it still the same rate: 50% crashes, 50% works.
[Edit]
I really think that SendKeys.Send acts differently on different computers with Windows 7.
Didn't want to answer my own question, but there is always a first time.
I decided to use a method similar to InputSimulator to achieve my goal and to avoid using SendKeys. Now, everything works perfectly on all machines.
I saw that InputSimulator is compatible with all my machines using Windows 7 and is using SendInput instead of SendMessage or SendKeys, so I used SendInput in my app.

how to save code and then calling it in a application

I have a question, is there a way to somehow save the code you write in some sort of file and call it in to my app? I have started to learn visual C# for a couple of weeks now and I've noticed as I am doing more complex applications the amount of code to write for a single operation is getting out of hand. For example i need to write things like
richtextbox1.text ="";
for multiple richtextboxes. I don't mind writing a lot of code but I wish I could somehow save it and call it by the file's name so I can be organized and be able to keep track of things. Is there such a way to do this?
example:
private void button_click(object sender, eventargs e)
{
do "from the file"
}
and that's all i need to write. all help is appreciated.
Would not calling a method be much easier?
Example:
private void restTextboxes()
{
richtextbox1.text = "";
richtextbox2.text = "";
}
private void button1_click(object sender, eventargs e)
{
resetTextboxes();
}
private void button2_click(object sender, eventargs e)
{
resetTextboxes();
}
Normally you put your code in other classes. You mention you have too much code in one file. The code in your file should only have something to do with the task. i.e MyApp form should only handle the very basics. Load/save and setting up the rest of the app.
Your code that has nothing to do with user interface you put in a so-called business object so you might reuse them someday.
The different sections in your ui, you put in smaller panels so these small panels will each have a file which will be nice and small. Repeat untill everything is in nice and small files.
That was just the 10k overview. In short a better question would be: how do I put different sections of my ui in userpanels. And how do I design classes with low coupling and high cohesion.
If you are using Visual Studio, you could have a look at using code snippets. These can be a bit annoying to define (though there are plugins/addons that can help, eg Snippet Designer), but very useful when writing code that has common elements. If using Visual Studio 2005/2008, see this article which links to some examples. If using Visual Studio 2010, have a look here. Other IDE's probably also support snippets in some form.
A code snippet is a small piece of code that can be modified when you insert it into your file via the IDE. You can do things like click once to add timing code around a block of code, or easily create getters and setters (though most IDEs seem to offer this anyway).
If the code you want to add does exactly what existing code does, I would recommend refactoring, as per Daniel's answer. However if some small part is different, code snippets can be very useful.

Windows Mobile Click Handler doesn't work

I have an urgent problem..I am developing a windows mobile 6.0 application and the menu item key (which I putted on left side to serve as a back button) only fires when I double click it or after several one clicks..but the items on the right side which in a menu works fine..
I see on the screen that it is clicked(phone vibrates) but it does not fall into the clickitem action.
going crazy someone helps please!!
it does not hit the actionMenuItem_Click_1() method at all if I dont double click
this.actionMenuItem.Text = "select";
this.actionMenuItem.Click += new System.EventHandler(this.actionMenuItem_Click_1);
private void actionMenuItem_Click_1(object sender, EventArgs e)
{
if (actionMenuItem.Text == "Back")
{
if (dialogStack.Count > 0)
{
navigateBack();
}
}
}
First of all - and this is very, very important - never, ever mark a question as urgent. Everyone who asks a question is looking for an answer here and they typically want or need the answer in a short period of time. Marking yours as urgent seems to say that you feel that your question is more important than every other question or that for some reason you should get some sort of priority treatment. My reaction when I see "urgent" is to ignore the question completely.
All answers here are given by volunteers for free. If you have some "urgent" issue that you need an immediate answer to, go pay someone to solve it where they have a contractual obligation to meet your schedule. Otherwise just ask your question.
Second, this is not a good question. The title needs to be a question. "URGENT" is not a question. You' also given us a very generalized behavior description, but we see absolutely no code. We don't see any description of what you've done to try to fix it. Not only are you asking us to give your question priority, you're also asking us to read your mind and divine the behaviors and code that only you see. We don't even know what kind of device this is or whenther it's WinMo Standard or Professional.
So let me shake shaking my magic 8-ball and see what it says about your issue given what we know...it says that your menu click handler calls some long-running method and is therefore interfering with subsequent clicks.
Have you tried debugging? what are the values of actionMenuItem.Text and dialogStack.Count when you step trough your code using the debugger?
Thanks for all answers, I solved it..I am doing some weird stuff in onpaint() that is interfering..

Categories