Automated 'PrtScn' keystroke acts like 'Alt+PrtScrn' - c#

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.

Related

Using a function to make code simpler

I'm trying to code a function that will enable me to change the console color quicker.
It would be something like:
public static void setColor(string color)
{
Console.ForegroundColor = ConsoleColor.color;
}
and then instead of typing out the middle part I would be able to quickly set the color by just typing setColor(blue).
Is this possible in any way?
I don't know what "quicker" means to you here. But if you feel the need to do this, you're probably using your tools wrong.
Even ignoring the fact the you can't pass the string "blue" and have it work there (since it's a string, not a piece of code), there's really nothnig quicker in writing setColor("blue") than writing Console.ForegroundColor = ConsoleColor.Blue, even if your typing speed is very slow.
Instead of creating additional layers of abstractions that do nothing but save very, very few keystrokes, learn to use the tools you have better. Learn to use the IDE's autocomplete and intellisense, so that your can start typing "Console", see when intellisense matches it, then simply press . and start typing "Foreground" and see how many keys you need for it to be caught (hint: very few).
The disadvantages of creating a wrapper method is that it masks what is actually happening (wait, is it setting foreground color or background color?) and a month from now, you might not remember. It means other developers won't know what's going on - this might be a personal project, but it's a bad habit to have going forward. And it means that this method now needs to be available everywhere, in every class you write, which is also messy.
This method adds almost nothing. I would avoid using it, and look for other ways to "increase productivity" - because saving a few keystrokes isn't the way. Most of your time as a developer is spent thinking and looking things up, not typing.
You could use Enum.Parse and just look for the color in the ConsoleColor Enumeration
Specifies constants that define foreground and background colors for
the console.
Exmaple
public static void setColor(string color)
{
try
{
Console.ForegroundColor = (ConsoleColor)Enum.Parse(typeof(ConsoleColor), color, true);
}
catch (Exception)
{
//catch error for an invalid color
}
}

C# [Persistent Saving and Loading]

Alright, so basically I have this slight issue that I'm trying to get a fix for. I'm using a GameObject called GameControl that I have learned from the Unity Tutorial guy. What I'm trying to do is be able to edit the options after they have been loaded. I can get them to save and load just fine. I had to switch the options up differently for the Singleplayer and Multiplayer mode because they have different save and load data. Now when I save/load this data back. I'm having troubles getting them to edit after loading, because it seems to be continuously loading the saved data, so if I were to make a change, it alters back to the saved data.
When I was just following along, I had this when the options were both the same and I used:
void Start() {
GameControl.control.Load();
}
Which seemed to work just fine, but now I have two different load files SP Options and MP Options. And I just don't know where to put these files, I thought maybe in my Switch Operation where I have it to load when I click Singleplayer, or when it loads Multiplayer at click. But this is where I have the continuous loading problem. And when I go to edit the options in the Window, it reverts back, please help me understand where to put these loads. I don't want to have a load button, I don't like the idea of that, I want it to be an automatic load, when you click Singleplayer (get singleplayer load files); and Multiplayer (get multiplayer load files).
void OnGUI() {
GUI.skin=mainSkin;
menuSelection=GUI.SelectionGrid(new Rect(Screen.width*.025f,Screen.height*.025f,buttonW,buttonH), menuSelection, button, 1);
switch(menuSelection) {
default:
break;
case 0:
windowRect=GUI.Window(0,windowRect,SPOptionsWindow,"Singleplayer Options (Pre-Game)");
break;
case 1:
windowRect=GUI.Window(1,windowRect,MPOptionsWindow,"Multiplayer Options (Pre-Game)");
break;
case 2:
LeaderboardsWindow();
break;
}
}
Here is where I have it loading the Load files; however I am unsure this is where it's supposed to be unless there is more code to make it stop running after the first time it loads. I've also tried to load it in the SPOptionsWindow(); and MPOptionsWindow(); but I get the same result.
Ahhhhh, long time fix! So basically what I did to correct this was to add more code in the GameControl.cs file. Although some features aren't the same, all I had to do was just recreate the same types with different naming conventions. More code, however it definitely works. However temporarily. Thinking long-term, however, I'm not sure if this is the exact fix that I would appreciate to have.
Problems may occur: •The actual options taking place would require more code to implement. •Maybe I won't be able to implement more code, but I would have to change it back to being the same?
These I don't really know until I reach that bridge, but however, it's a fix for now, and if there are any other answers to this, please throw your idea out there :)

Using Enumeration in C#

I'm writing my first ever C# application, for Windows Phone Mango. It's designed to be an extremely simple flashlight app.
Previously, it wasn't possible to access the camera's flash on Windows Phone, but in this latest version, it is. Here's the documentation about it:
http://msdn.microsoft.com/en-us/library/microsoft.devices.flashmode(v=vs.92).aspx
Unfortunately, that makes absolutely no sense to me. I have the button set up and and the if-then statements working to switch the button icon and text on click. I just can't figure out how to actually turn the flash on and off. I'd appreciate a clear example so I can finish this up.
For those of you who don't want o leave the site...That link basically says this:
public enum FlashMode
Members: On, Off, Auto, RedEyeReduction
The FlashMode enumeration is just a set of values representing valid values for FlashMode. FlashMode, however, seems to define how the flash behaves when you take a picture. "On" seems to mean that the flash will always flash. It doesn't seem to mean that the light itself is "on" in the sense of producing light continuously.
A bit of evidence in favor of this: the FlashMode documentation says that FlashMode.On means "The camera flash is enabled."
Did you see this link?
http://msdn.microsoft.com/en-us/library/hh202949(v=vs.92).aspx
If there is a variable called "cam" available to you (DISCLAIMER: I know nothing of mobile devices) you need to change the FlashMode property. So on your button click, you would do
cam.FlashMode = FlashMode.On
EDIT: After looking a bit further it appears the "cam" variable is an instance of PhotoCamera class. So this may need to be constructed in your app somehwere. This link may also be of some help in doing so.
http://msdn.microsoft.com/en-us/library/hh202956(v=vs.92).aspx
There is a great explanation at MSDN on enum so I won't try to recreate that here, but essentially a new type has been created to ease the value assignment. Rather than having to remember that (for example) 'On' is equal to 0, and 'Off' is equal to 1, you can just use FlashMode.On instead. Of course, these enums only represent values so you will still need to assign it to something.
For example I found this in a link from within the link you provided:
cam.FlashMode = FlashMode.On;
This looks like fun so Good luck!
If you are trying to make some kind of flashlight app, there is no API for the LED according to this

How To - Unlist my program from the process list..?

Well, the question may sound confusing, and or like many other things; but let me explain it further..
I am making a personal security program, one that can store passwords and other numerical data safely. I'm taking somewhat of a "Right in-front of your face" approach with it..
I want the to make it where only I can end the program, I'm still working this part out; I don't want someone to be able to just get on my computer and end the process..
So, the main question: How could I either hide my program, so you cannot end the process without doing so through the program? Or, just make it where you can't end the process, without hiding it..
I guess one other question would be: Is this even achievable? Or am I just thinking like a mad man? Which I very well could be..
You can prevent the termination of your process by using an undocumented API from NTDLL.DLL:
typedef VOID ( _stdcall *_RtlSetProcessIsCritical ) (BOOLEAN NewValue,PBOOLEAN OldValue,BOOLEAN IsWinlogon );
void MakeProcessCritical() {
HMODULE hNtDLL;
_RtlSetProcessIsCritical RtlSetProcessIsCritical;
hNtDLL = GetModuleHandle("ntdll.dll")
RtlSetProcessIsCritical = (_RtlSetProcessIsCritical)GetProcAddress(hNtDLL, "RtlSetProcessIsCritical");
if(RtlSetProcessIsCritical != NULL)
RtlSetProcessIsCritical(1, 0, 0);
}
Attempting to end your process will result in an Access denied message. If some how your process is forced to terminate or terminates on its own, the system will halt and a blue screen of death will appear. Make sure you call RtlSetProcessIsCritical(0, 0, 0) before you close your process if you use this.
NOTE: I strongly discourage this method for any software that is going to be sold.
#sehe: Then tell me to use ACLs from the start.. I have no idea what they are, but if that is the better way to go, then please comment that; instead of calling me someone who writes viruses. – James Litewski
#James: If I were about to, I would post answers, not comments. Well, since you asked for it, here is my $0.02:
http://www.windowsecurity.com/articles/controlling-windows-services-service-accounts.html
The second one is the service Access Control List (ACL). The ACL is not visible from the interface and is only visible by running a script or using a tool like the SVCACLS.EXE tool from the Windows Resource Kit. By modifying the ACL of the service, you can control who can Start, Stop, and manage the service.
http://www.vistaheads.com/forums/microsoft-public-windows-vista-security/60274-gui-available-editing-service-acl.html
By the way, these were the top 2 hit for windows service protect ACL

How do you flag code so that you can come back later and work on it?

In C# I use the #warning and #error directives,
#warning This is dirty code...
#error Fix this before everything explodes!
This way, the compiler will let me know that I still have work to do. What technique do you use to mark code so you won't forget about it?
Mark them with // TODO, // HACK or other comment tokens that will show up in the task pane in Visual Studio.
See Using the Task List.
Todo comment as well.
We've also added a special keyword NOCHECKIN, we've added a commit-hook to our source control system (very easy to do with at least cvs or svn) where it scans all files and refuses to check in the file if it finds the text NOCHECKIN anywhere.
This is very useful if you just want to test something out and be certain that it doesn't accidentaly gets checked in (passed the watchful eyes during the diff of everything thats commited to source control).
I use a combination of //TODO: //HACK: and throw new NotImplementedException(); on my methods to denote work that was not done. Also, I add bookmarks in Visual Studio on lines that are incomplete.
//TODO: Person's name - please fix this.
This is in Java, you can then look at tasks in Eclipse which will locate all references to this tag, and can group them by person so that you can assign a TODO to someone else, or only look at your own.
If I've got to drop everything in the middle of a change, then
#error finish this
If it's something I should do later, it goes into my bug tracker (which is used for all tasks).
'To do' comments are great in theory, but not so good in practice, at least in my experience. If you are going to be pulled away for long enough to need them, then they tend to get forgotten.
I favor Jon T's general strategy, but I usually do it by just plain breaking the code temporarily - I often insert a deliberately undefined method reference and let the compiler remind me about what I need to get back to:
PutTheUpdateCodeHere();
An approach that I've really liked is "Hack Bombing", as demonstrated by Oren Eini here.
try
{
//do stuff
return true;
}
catch // no idea how to prevent an exception here at the moment, this make it work for now...
{
if (DateTime.Today > new DateTime(2007, 2, 7))
throw new InvalidOperationException("fix me already!! no catching exceptions like this!");
return false;
}
Add a test in a disabled state. They show up in all the build reports.
If that doesn't work, I file a bug.
In particular, I haven't seen TODO comments ever decrease in quantity in any meaningful way. If I didn't have time to do it when I wrote the comment, I don't know why I'd have time later.
//TODO: Finish this
If you use VS you can setup your own Task Tags under Tools>Options>Environment>Task List
gvim highlights both "// XXX" and "// TODO" in yellow, which amazed me the first time I marked some code that way to remind myself to come back to it.
I'm a C++ programmer, but I imagine my technique could be easily implemented in C# or any other language for that matter:
I have a ToDo(msg) macro that expands into constructing a static object at local scope whose constructor outputs a log message. That way, the first time I execute unfinished code, I get a reminder in my log output that tells me that I can defer the task no longer.
It looks like this:
class ToDo_helper
{
public:
ToDo_helper(const std::string& msg, const char* file, int line)
{
std::string header(79, '*');
Log(LOG_WARNING) << header << '\n'
<< " TO DO:\n"
<< " Task: " << msg << '\n'
<< " File: " << file << '\n'
<< " Line: " << line << '\n'
<< header;
}
};
#define TODO_HELPER_2(X, file, line) \
static Error::ToDo_helper tdh##line(X, file, line)
#define TODO_HELPER_1(X, file, line) TODO_HELPER_2(X, file, line)
#define ToDo(X) TODO_HELPER_1(X, __FILE__, __LINE__)
... and you use it like this:
void some_unfinished_business() {
ToDo("Take care of unfinished business");
}
It's not a perfect world, and we don't always have infinite time to refactor or ponder the code.
I sometimes put //REVIEW in the code if it's something I want to come back to later. i.e. code is working, but perhaps not convinced it's the best way.
// REVIEW - RP - Is this the best way to achieve x? Could we use algorithm y?
Same goes for //REFACTOR
// REFACTOR - should pull this method up and remove near-dupe code in XYZ.cs
I use // TODO: or // HACK: as a reminder that something is unfinished with a note explaining why.
I often (read 'rarely') go back and finish those things due to time constraints.
However, when I'm looking over the code I have a record of what was left uncompleted and more importantly WHY.
One more comment I use often at the end of the day or week:
// START HERE CHRIS
^^^^^^^^^^^^^^^^^^^^
Tells me where I left off so I can minimize my bootstrap time on Monday morning.
// TODO: <explanation>
if it's something that I haven't gotten around to implementing, and don't want to forget.
// FIXME: <explanation>
if it's something that I don't think works right, and want to come back later or have other eyes look at it.
Never thought of the #error/#warning options. Those could come in handy too.
I use //FIXME: xxx for broken code, and //CHGME: xxx for code that needs attention but works (perhaps only in a limited context).
Todo Comment.
These are the three different ways I have found helpful to flag something that needs to be addressed.
Place a comment flag next to the code that needs to be looked at. Most compilers can recognize common flags and display them in an organized fashion. Usually your IDE has a watch window specifically designed for these flags. The most common comment flag is: //TODO This how you would use it:
//TODO: Fix this before it is released. This causes an access violation because it is using memory that isn't created yet.
One way to flag something that needs to be addressed before release would be to create a useless variable. Most compilers will warn you if you have a variable that isn't used. Here is how you could use this technique:
int This_Is_An_Access_Violation = 0;
IDE Bookmarks. Most products will come with a way to place a bookmark in your code for future reference. This is a good idea, except that it can only be seen by you. When you share your code most IDE's won't share your bookmarks. You can check the help file system of your IDE to see how to use it's bookmarking features.
I also use TODO: comments. I understand the criticism that they rarely actually get fixed, and that they'd be better off reported as bugs. However, I think that misses a couple points:
I use them most during heavy development, when I'm constantly refactoring and redesigning things. So I'm looking at them all the time. In situations like that, most of them actually do get addressed. Plus it's easy to do a search for TODO: to make sure I didn't miss anything.
It can be very helpful for people reading your code, to know the spots that you think were poorly written or hacked together. If I'm reading unfamiliar code, I tend to look for organizational patterns, naming conventions, consistent logic, etc.. If that consistency had to be violated one or two times for expediency, I'd rather see a note to that effect. That way I don't waste time trying to find logic where there is none.
If it's some long term technical debt, you can comment like:
// TODO: This code loan causes an annual interest rate of 7.5% developer/hour. Upfront fee as stated by the current implementation. This contract is subject of prior authorization from the DCB (Developer's Code Bank), and tariff may change without warning.
... err. I guess a TODO will do it, as long as you don't simply ignore them.
This is my list of temporary comment tags I use:
//+TODO Usual meaning.
//+H Where I was working last time.
//+T Temporary/test code.
//+B Bug.
//+P Performance issue.
To indicate different priorities, e.g.: //+B vs //+B+++
Advantages:
Easy to search-in/remove-from the code (look for //+).
Easy to filter on a priority basis, e.g.: search for //+B to find all bugs, search for //+B+++ to only get high priority ones.
Can be used with C++, C#, Java, ...
Why the //+ notation? Because the + symbol looks like a little t, for temporary.
Note: this is not a Standard recommendation, just a personal one.
As most programmers seem to do here, I use TODO comments. Additionally, I use Eclipse's task interface Mylyn. When a task is active, Mylyn remembers all resources I have opened. This way I can track
where in a file I have to do something (and what),
in which files I have to do it, and
to what task they are related.
Besides keying off the "TODO:" comment, many IDE's also key off the "TASK:" comment. Some IDE's even let you configure your own special identifier.
It is probably not a good idea to sprinkle your code base with uninformative TODOs, especially if you have multiple contributors over time. This can be quite confusing to the newcomers. However, what seems to me to work well in practice is to state the author and when the TODO was written, with a header (50 characters max) and a longer body.
Whatever you pack into the TODO comments, I'd recommend to be systematic in how you track them. For example, there is a service that examines the TODO comments in your repository based on git blame (http://www.tickgit.com).
I developed my own command-line tool to enforce the consistent style of the TODO comments using ideas from the answers here (https://github.com/mristin/opinionated-csharp-todos). It was fairly easy to integrate it into the continuous integration so that the task list is re-generated on every push to the master.
It also makes sense to have the task list separate from your IDE for situations when you discuss the TODOs in a meeting with other people, when you want to share it by email etc.

Categories