C# SendKeys and Microsoft SQL Server Management Studio 2012 (SSMS) - clipboard

Solved! See [SOLUTION]
Thanks for any help you can provide. It's much appreciated!
In a nutshell: I'm trying to send Ctrl+V to SSMS 2012 with SendKeys.Send("^{v}"), but it doesn't work. It's working fine with Notepad, UltraEdit, Word, Excel, Chrome, you name it. It even works in Microsoft Visual Studio 2010.
In details: I have an application that runs in the background. Using a keyboard shortcut, this application displays a popup window with options. Depending on the option I choose it saves what's related to it into the clipboard. I then close that popup window, get the new foreground window (which should be the one I had before displaying the popup) and try to paste what's in my clipboard with SendKeys.
It works with pretty much every application I try it with, except SSMS
If I manually press Ctrl+V it pastes what I have in my clipboard (text usually)
I've added some code to display the title of the window I got with the GetForegroundWindow and it does give me the correct SSMS window
What's sad about all this is that once in a while (very rarely), the text is correctly pasted in SSMS, but it doesn't work the second after.
I never get the MessageBox saying the SetForegroundWindow failed.
If I replace the single SendKey with 3 SendKeys to send "A", "B" and "C", B and C are sent but not A. Yes I've tried using a sleep thinking it needed time to write the first SendKey, but that didn't change anything.
I did try SendKeys.SendWait instead, but didn't get different results.
Here's the code from the moment I close the popup
this.Close();
IntPtr handle = GetForegroundWindow();
if (!handle.Equals(IntPtr.Zero))
{
if (SetForegroundWindow(handle))
{
//Optionnal just to show the window title
const int nChars = 256;
StringBuilder Buff = new StringBuilder(nChars);
if (GetWindowText(handle, Buff, nChars) > 0)
{
MessageBox.Show(Buff.ToString());
}
//[SOLUTION] Sending a useless key seems to solve my SSMS problem without affecting the other applications.
SendKeys.Send("{F14}");
//Sending Ctrl+V
SendKeys.Send("^{v}");
}
else
{
MessageBox.Show("SetForegroundWindow failed");
}
}
Hope someone can help.
Thanks in advance!

See http://msdn.microsoft.com/en-us/library/system.windows.forms.sendkeys.aspx
...
The SendKeys class is susceptible to timing issues, which some developers have had to work around. The updated implementation is still susceptible to timing issues, but is slightly faster and may require changes to the workarounds. The SendKeys class tries to use the previous implementation first, and if that fails, uses the new implementation. As a result, the SendKeys class may behave differently on different operating systems. Additionally, when the SendKeys class uses the new implementation, the SendWait method will not wait for messages to be processed when they are sent to another process.
...

Related

How do I write to the CommandPrompt from Windows GUI?

Operating Environment: Windows 7, Visual Studio 2010, CLR GUI.
So I've been given the unglorious task of enhancing a GUI application that is started from a command prompt. Because it is. Because poor design decisions by previous implementers. Anyway, it launches one of several GUIs depending upon the input arguments.
I'd like to be able to print back to the same command prompt window if (when) the user types something that the code doesn't understand.
Here's what I've tried (none of which output anything):
int main( array<System::String^>^ args )
{
Application::EnableVisualStyles();
Application::SetCompatibleTextRenderingDefault(false);
OutputDebugString("hello");
Trace::WriteLine("hello");
Debug::Trace::WriteLine("hello");
Console::WriteLine("hello");
std::cout << "hello";
printf("hello");
return 0;
}
Thanks in advance!
Update: I don't want to use AllocConsole(), as that opens a new console that disappears along with all of the data when the application exits. Similarly, a pop-up message box won't work. I'm looking for a way to make the output persistent.
The only way I can get output from the application to date is via a message box (non-persistent) or opening a new console that disappears when the application exits (via AllocConsole() ). And I'm running from a command prompt, not the debugger's "Play" button.
Update
Why the down-vote for not doing research? I spent a day trying to solve this, looking through dozens of posts trying to find a solution, and to date I've found others looking for the same answer, but not finding it. AllocConsole() or changing the project type is always the solution, but neither is a solution for me.
Update
I added the "full code", which is the 2 statements. THAT IS ALL THE CODE. So simple. I'm skipping the start of the GUI because I don't care about that right now, I just want it to print back to the console where the application was started. The most basic HelloWorld. If there are project settings I need to post, I don't know which ones would be relevant. This is where I want to print to the console, before the GUI is ever up. I can't show the GUI if there is an error in the user input.
Right click on the project, select Properties
Under Linker -> System, Change Subsystem from Windows to Console.
A Windows subsystem application cannot write to console, but by changing the subsystem to Console (which can write to the calling console), the Form part of the application can still work (tested in Visual Studio 2010).

UFT - Object Identification not working on Run Time

I have written a code for Web page. The process requires me to click on a weblink which opens up a new window, then perform some operations on the browser window. Then I close the new browser. This is repeated multiple times in the code. All the elements on all the browser windows are normally identifiable using the object spy. However, intermittently during run time when a new browser window opens up the elements on the page are not getting recognized (hence it throws errors). When i go into the debug mode and try using the object spy the maximum identification i can capture is Browser(<>).Page(<>). Nothing in the page is getting recognized.
Now if i close this browser and reopen it and check again, the elements on the page are getting captured by the object spy and i can continue with my script execution. Sometimes I have to close and reopen multiple times for it to work.
Is there any way to handle this scenario. check for object identifications on the run time maybe. Dunno if it this is any relevant but i am not making use of the OR in my project.
Thanks in advance.
This sounds like a bug in UFT and you should contact HP's support.
A workaround if you know where the problem is probable to appear is to add Browser("<name>").RefreshWebSupport. This is an undocumented feature of UFT that sometimes helps in cases like this.

How would one display a prompt after installation of an extension?

When my add-on installs it needs to prompt the user to get a username or something like that. After that it stores it and shouldn't ask again. Where would I place this prompt? install.rdf? browser.xul?
There is no explicit mechanism to run code when the extension installs - you should simply do it when your extension runs for the first time. The easiest approach would be checking whether the user name is already set up. If it is not - show the prompt.
It is not recommended to show a modal dialog, those are extremely annoying to users, especially when they suddenly appear during Firefox start-up. You should instead open your page in a tab. A slight complication: Firefox might be restoring a previous session when it starts up. If you open your page too early the session restore mechanism might replace it. So you should wait for the sessionstore-windows-restored notification, something like this should work:
Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
Components.utils.import("resource://gre/modules/Services.jsm");
var observer = {
observe: function(subject, topic, data)
{
Services.obs.removeObserver("sessionstore-windows-restored", this);
var browser = window.getBrowser();
browser.loadOneTab("chrome://...", {inBackground: false});
},
QueryInterface: XPCOMUtils.generateQI([
Components.interfaces.nsIObserver,
Components.interfaces.nsISupportsWeakReference
])
};
Services.obs.addObserver("sessionstore-windows-restored", observer, true);
A final complication is that your code is probably running from a browser window overlay - meaning that there will be multiple instances of your code if the session restored contains more than one window. You probably want the code above to run only once however rather than opening your first-run page in every browser window. So you will have to coordinate somehow, maybe via preferences. A slightly more complicated but better solution would be having a JavaScript code module in your extension - code modules are only loaded once so you wouldn't have a coordination issue there.
Try using an addonlistener https://developer.mozilla.org/en/Addons/Add-on_Manager/AddonListener#onInstalling%28%29
Or by using the preferences: https://stackoverflow.com/a/958944/1360985

Disable/Change Firefox Safe Mode Hotkey (Shift)

Is there any way to change the firefox shift hotkey that makes firefox start in safe mode? I've set up some unit tests using Selenium and PHPUnit, but if I'm working on the machine while the tests are running then I frequently find I'm pressing shift as I type (holding shift as I select blocks of code is another big offender). This causes the test to fail (and time out) even if you click past the safe mode prompt that pops up.
Is there a way to disable this hot key, or change the key to something that I'd use less often?
I've also met with this problem and didn't find a solution. It seems that it is still an open issue: Mozilla Forums thread, Bug 653410, Bug 644175 and so on. As a workaround you can install firefox 3.6 as this feature was implemented since firefox 4, but probably this will not suite you.
Mozilla finally added an environment variable to control this behavior. Unfortunately, configuring this environment variable in a way that applies to the overall graphical system, rather than merely a bash session, is a bit difficult. This used to be done via /etc/launchd.conf, but macOS dropped support for this in v10.10. Fortunately, systemctl offers a .plist file system which can define run programs and define system-wide environment variables at boot, so I published this working .plist file, with instructions for installing and removing it:
https://github.com/mcandre/dotfiles/blob/master/setenv.MOZ_DISABLE_SAFE_MODE_KEY.plist
This is awesome for me, because I like to launch my web browser from anywhere in the GUI with Control+Alt+G via QuickSilver, which of course includes the Alt modifier that Firefox tends to interpret as signaling safe mode.
Until Bug 653410 is fixed, the best workaround I can come up with is to detect when safe mode is launched and handle it in the best way fit for your particular purposes. This may mean killing the Firefox process and launching again, or it may mean warning the user, or both. When Firefox is launched into safe mode, it writes "LastVersion=Safe Mode" to its compatibility.ini file in its profile directory. An example C# function to watch for this is given below.
FileSystemWatcher safeModeWatcher;
private void watchSafeMode()
{
string profiles = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Mozilla", "Firefox", "Profiles");
string defaultProfile = Directory.GetDirectories(profiles, "*default*")[0];
safeModeWatcher = new FileSystemWatcher(defaultProfile, "compatibility.ini");
safeModeWatcher.NotifyFilter = NotifyFilters.LastWrite;
safeModeWatcher.Changed += delegate(object s, FileSystemEventArgs e)
{
if (File.ReadAllText(e.FullPath).Contains("LastVersion=Safe Mode"))
{
// safe mode!
System.Diagnostics.Trace.WriteLine("safe mode detected!");
// TODO kill Firefox and launch again, or whatever makes sense for you
}
};
safeModeWatcher.EnableRaisingEvents = true;
// ...
// TODO Dispose safeModeWatcher when done
}

How do I disable the 'Debug / Close Application' dialog on Windows Vista?

When an application crashes on Windows and a debugger such as Visual Studio is installed the following modal dialog appears:
[Title: Microsoft Windows]
X has stopped working
A problem caused the program to stop
working correctly. Windows will close
the program and notify you if a
solution is available.
[Debug][Close Application]
Is there a way to disable this dialog? That is, have the program just crash and burn silently?
My scenario is that I would like to run several automated tests, some of which will crash due to bugs in the application under test. I don't want these dialogs stalling the automation run.
Searching around I think I've located the solution for disabling this on Windows XP, which is nuking this reg key:
HKLM\Software\Microsoft\Windows NT\CurrentVersion\AeDebug\Debugger
However, that did not work on Windows Vista.
To force Windows Error Reporting (WER) to take a crash dump and close the app, instead of prompting you to debug the program, you can set these registry entries:
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\Windows Error Reporting]
"ForceQueue"=dword:00000001
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\Windows Error Reporting\Consent]
"DefaultConsent"=dword:00000001
After this is set, when your apps crash, you should see *.hdmp and *.mdmp files in:
%ALLUSERSPROFILE%\Microsoft\Windows\WER\
See here:
http://msdn.microsoft.com/en-us/library/bb513638.aspx
regedit
DWORD HKLM or HKCU\Software\Microsoft\Windows\Windows Error Reporting\DontShowUI = "1"
will make WER silently report. Then you can set
DWORD HKLM or HKCU\Software\Microsoft\Windows\Windows Error Reporting\Disabled = "1"
to stop it from talking to MS.
I'm not sure if this refers to exactly the same dialog but here is an alternative approach from Raymond Chen:
DWORD dwMode = SetErrorMode(SEM_NOGPFAULTERRORBOX);
SetErrorMode(dwMode | SEM_NOGPFAULTERRORBOX);
I had to disable this for release automation work on Windows 64-bits for Firefox and I did the following:
gpedit.msc
Computer configuration -> Administrative Templates
Windows Components -> Windows Error Reporting
Set "Prevent display of the user interface for critical errors" to Enabled
It is similar what was accomplished for Customer Experience reporting in:
http://www.blogsdna.com/2137/fix-windows-installer-explorer-update-has-stopped-working-in-windows-7.htm
In my context, I only want to suppress the popup for my unit tests and not for the entire system. I've found that a combination of functions are needed in order to suppress these errors, such as catching unhandled exceptions, suppressing run time checks (such as the validity of the stack pointer) and the error mode flags. This is what I've used with some success:
#include <windows.h>
#include <rtcapi.h>
int exception_handler(LPEXCEPTION_POINTERS p)
{
printf("Exception detected during the unit tests!\n");
exit(1);
}
int runtime_check_handler(int errorType, const char *filename, int linenumber, const char *moduleName, const char *format, ...)
{
printf("Error type %d at %s line %d in %s", errorType, filename, linenumber, moduleName);
exit(1);
}
int main()
{
DWORD dwMode = SetErrorMode(SEM_NOGPFAULTERRORBOX);
SetErrorMode(dwMode | SEM_NOGPFAULTERRORBOX);
SetUnhandledExceptionFilter((LPTOP_LEVEL_EXCEPTION_FILTER)&exception_handler);
_RTC_SetErrorFunc(&runtime_check_handler);
// Run your tests here
return 0;
}
In WPF application
[DllImport("kernel32.dll", SetLastError = true)]
static extern int SetErrorMode(int wMode);
[DllImport("kernel32.dll")]
static extern FilterDelegate SetUnhandledExceptionFilter(FilterDelegate lpTopLevelExceptionFilter);
public delegate bool FilterDelegate(Exception ex);
public static void DisableChashReport()
{
FilterDelegate fd = delegate(Exception ex)
{
return true;
};
SetUnhandledExceptionFilter(fd);
SetErrorMode(SetErrorMode(0) | 0x0002 );
}
You have to implement an unhandled exception filter which simply quits your application, then set that filter function with SetUnhandledExceptionFilter().
If you're using the secure CRT, you also have to provide your own invalid parameter handler and set this with _set_invalid_parameter_handler().
This blog post has some information too:
http://blog.kalmbachnet.de/?postid=75
During test you can run with a 'debugger' like ADPlus attached which can be configured in many useful ways to collect data (minidumps) on errors and yet prevent the modal dialog problems you state above.
If you want to get some useful information when your app crashes in production you can configure Microsoft Error reporting to get something similar to ADPlus data.
This isn't a direct answer to the question since this is a workaround and the question is about how to disable that feature, but in my case, I'm a user on a server with limited permissions and cannot disable the feature using one of the other answers. So, I needed a workaround. This will likely work for at least some others who end up on this question.
I used autohotkey portable and created a macro that once a minute checks to see if the popup box exists, and if it does, clicks the button to close the program. In my case, that's sufficient, and leaves the feature on for other users. It requires that I start the script when I run the at-risk program, but it works for my needs.
The script is as follows:
sleep_duration = 60000 ; how often to check, in milliseconds.
; 60000 is a full minute
Loop
{
IfWinExist, ahk_class #32770 ; use autohotkey's window spy to confirm that
; ahk_class #32770 is it for you. This seemed to be consistent
; across all errors like this on Windows Server 2008
{
ControlClick, Button2, ahk_class #32770 ; sends the click.
; Button2 is the control name and then the following
; is that window name again
}
Sleep, sleep_duration ; wait for the time set above
}
edit: A quick flag. When other things are up, this seems to attempt to activate controls in the foreground window - it's supposed to send it to the program in the background. If I find a fix, I'll edit this answer to reflect it, but for now, be cautious about using this and trying to do other work on a machine at the same time.
After trying everything else on the internet to get rid of just in time debugger, I found a simple way that actually worked and I hope will help someone else.
Go to Control Panel
Go to Administrative Tools
Go to Services
Look down the list for Machine Debug Manager
Right Click on it and click on Properties
Under the General Tab, look for Start Up Type
Click on Disable.
Click on Apply and OK.
I haven't seen the debugger message since, and my computer is running perfectly.
Instead of changing values in the registry you can completly disable the error reporting on Windows Server 2008 R2, Windows Server 2012 and Windows 8 with: serverWerOptin /disable
https://technet.microsoft.com/en-us/library/hh875648(v=ws.11).aspx

Resources