Suppress Process Popup in .NET - c#

Our user panel runs all of our software as services. For whatever reason though, the Mumble voice software creates a popup when you run it with an administrator password set in the command line. Someone posted an alternative by using a bat file that runs two processes as a work around, but is there any way to just suppress the popup message using .NET? I have written a lot of launcher type apps to fix things like this, but I have no idea how I could suppress this message.
Here is what the .bat file looks like from the workaround.
set /p VAR= < superadmin.txt
start murmur2.exe -supw %var%
ping 0.0.0.0 -n 3 > NUL
tskill murmur2
murmur.exe

You can try to monitor open windows and close popup via winapi when it shows up
[DllImport("user32.dll")]
public static extern int FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll")]
public static extern int SendMessage(int hWnd, uint Msg, int wParam, int lParam);
public const int WM_COMMAND = 0x0112;
public const int WM_CLOSE = 0xF060;
int handle = FindWindow(lpClassName, lpWindowName);
SendMessage(handle, WM_COMMAND, WM_CLOSE, 0);

Related

SendKeys.SendWait in English when the keyboard set to other language

In my application i am using SendKeys.SendWait to send text to screen:
SendKeys.SendWait("password");
The text is on English but when the keyboard set to other language the text that SendKeys.SendWait type is set in other language and not in English
Any suggestions how to make sure that the text will set only in English ?
I did a quick test using SendKeys.Send to send text to a couple of input fields. It sends the same text regardless of whether I have the keyboard in English or another language, so I'm not sure why you see a different result. Example:
SendKeys.Send("username");
SendKeys.Send("{TAB}");
SendKeys.Send("påsswørd");
SendKeys.SendWait("{ENTER}");
One possibility is that you could change the keyboard to English temporarily before calling SendKeys, then set it back to whatever it was before. There is an excellent example of the technique in this answer.
Another option is to use Win32 API functions to send messages to the window. The problem will be how to find the right windows to send the text to though. I'm not sure it could be done reliably. Here's an example (not tested):
using System.Runtime.InteropServices;
[DllImport("user32.dll")]
static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll")]
public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
[DllImport("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, int wMsg, int wParam, string lParam);
// Windows message constants
const int WM_SETTEXT = 0x000C;
public void DoLogin(string username, string password)
{
// Get handle for current active window
IntPtr hWndMain = GetForegroundWindow();
if (!hWndMain.Equals(IntPtr.Zero))
{
IntPtr hWnd;
// Here you would need to find the username text input window
if ((hWnd = FindWindowEx(hWndMain, IntPtr.Zero, "UserName", "")) != IntPtr.Zero)
// Send the username text to the active window
SendMessage(hWnd, WM_SETTEXT, 0, username);
// Here you would need to find the password text input window
if ((hWnd = FindWindowEx(hWndMain, IntPtr.Zero, "Password", "")) != IntPtr.Zero)
// Send the password text
SendMessage(hWnd, WM_SETTEXT, 0, password);
// Send ENTER key to invoke login
SendKeys.SendWait("{ENTER}");
}
}

Close open Explorer windows without terminating explorer.exe

I've tried searching but nothing really matches my demand.
I don't want explorer.exe to be terminated or restarted.
I just want any open explorer windows to close.
[DllImport("user32.dll")]
private static extern bool EnumWindows(EnumWindowsDelegate lpEnumFunc, IntPtr lParam);
[DllImport("user32.dll")]
private static extern IntPtr GetWindowThreadProcessId(IntPtr hWnd, out IntPtr lpdwProcessId);
[DllImport("user32.dll")]
private static extern uint RealGetWindowClass(IntPtr hwnd, StringBuilder pszType, uint cchType);
[DllImport("user32.dll")]
static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);
static uint WM_CLOSE = 0x10;
private delegate bool EnumWindowsDelegate(IntPtr hwnd, IntPtr lParam);
private static bool EnumWindowsCallback(IntPtr hwnd, IntPtr lParam)
{
IntPtr pid = new IntPtr();
GetWindowThreadProcessId(hwnd, out pid);
var wndProcess = System.Diagnostics.Process.GetProcessById(pid.ToInt32());
var wndClass = new StringBuilder(255);
RealGetWindowClass(hwnd, wndClass, 255);
if (wndProcess.ProcessName == "explorer" && wndClass.ToString() == "CabinetWClass")
{
//hello file explorer window...
SendMessage(hwnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero); // ... bye file explorer window
}
return (true);
}
static void Main()
{
EnumWindowsDelegate childProc = new EnumWindowsDelegate(EnumWindowsCallback);
EnumWindows(childProc, IntPtr.Zero);
Console.ReadKey();
}
edit:
so i guess the only interesting thing is the callback which will be called by windows for each enumerated window (handle of said window in hwnd)
GetWindowThreadProcessId provides us with the processid for a given window handle
GetProcessById then provides us with a process object to read things like the process name from
RealGetWindowClass provides us with the registered class name for a given window handle
finally we can look to see if the process for the current window is the explorer and if the window class is "CabinetWClass", which is the window class for the normal file explorer window
last but not least, if our check is ok, send a WM_CLOSE message to kindly ask the window to close itself...
The following alternative uses the COM API of the Shell object to retrieve and identify File Explorer windows. It requires the addition of the COM references to:
Microsoft Shell Controls And Automation
Microsoft Internet Controls
The object returned by Shell.Windows method is an IEnumerable. Each object in the collection is a SHDocVw.InternetExplorer instance. If the Document object is a Shell32.ShellFolderView, then the explorer is a File Explorer.
private static void CloseExplorerWindows()
{
Shell32.Shell shell = new Shell32.Shell();
// ref: Shell.Windows method
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb774107(v=vs.85).aspx
System.Collections.IEnumerable windows = shell.Windows() as System.Collections.IEnumerable;
if (windows != null)
{
// ref: ShellWindows object
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb773974(v=vs.85).aspx
foreach (SHDocVw.InternetExplorer window in windows)
{
object doc = window.Document;
if (doc != null && doc is Shell32.ShellFolderView)
{
window.Quit(); // closes the window
}
}
}
}
public static void CloseExplorerWindows() => EnumWindows(new EnumWindowsProc(EnumTheWindows), IntPtr.Zero);
private delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
private static extern int GetWindowText(IntPtr hWnd, StringBuilder strText, int maxCount);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
private static extern int GetWindowTextLength(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern bool EnumWindows(EnumWindowsProc enumProc, IntPtr lParam);
[DllImport("user32.dll")]
private static extern bool IsWindowVisible(IntPtr hWnd);
[DllImport("user32.dll", SetLastError = true)]
static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);
static uint WM_CLOSE = 0x10;
private static bool EnumTheWindows(IntPtr hWnd, IntPtr lParam)
{
int size = GetWindowTextLength(hWnd);
if (size++ > 0 && IsWindowVisible(hWnd))
{
var sb = new StringBuilder(size);
GetWindowText(hWnd, sb, size);
var threadID = GetWindowThreadProcessId(hWnd, out var processID);
var s = System.Diagnostics.Process.GetProcessById((int)processID).ProcessName;
if (s == "explorer" && sb.ToString() != "Program Manager")
SendMessage(hWnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
}
return true;
}
By default, explorer runs as single process, and any windows that open are just a thread of the process.
Normally, to close a program, you'd send a close message to the process. In this case, closing explorer.exe will close all explorer windows.
To close individual windows, you'd open each window via it's own process.
This can be done via registry setting or enabling under View->Options->View->Advanced Settings: "Launch ... separate process"
a) Find PID (process ID) of window you wanna close.
via taskmanager:
1. In list of processes, click the arrow to the left of "Windows Explorer"
2. Check the window name matches the window you wanna close
3. Right click on "Windows Explorer", click "Go to Details"
4. Record the pid
via CMD:
tasklist /V /FI "IMAGENAME eq explorer.exe"
If each explorer window is open in it's own process, the above command would display the window title in the last column.
Otherwise "N/A" would be displayed.
The pid of all explorer windows would be the same. Explorer.exe processes have their own pid, and title "N/A"
If 'separate process' has been enabled eg. via Folder View option, then each window can be closed via the process id & filter option of taskkill.
To close, the desired window has to be activated first, otherwise closing with pid will close the last active window, or closing with window title filter will give error:
INFO: No tasks running with the specified criteria.
b) taskkill /pid <pid>
will close the last active window.
Repeating this command will the next window.
or taskkill /im explorer.exe /fi "windowtitle eq <window name>"
or taskkill /fi "IMAGENAME eq explorer.exe" /fi "windowtitle eq <window name>"
< window name > is not case sensitive
If full path in title bar has been enabled in Folder view, then include full path or wildcards.
To close all explorer windows:
taskkill /im explorer.exe
Notes:
To activate explorer window, issue same command to open the window, if window reusing is enabled.
The pid of explorer window(ing) process is in the last row of the response table, in column "PID"; can be accessed via FOR loop.
A vbs workaround to close window from #HelpingHand: https://superuser.com/questions/1263315/how-to-close-a-particular-opened-folder-using-cmd-or-batch-file
A vbs workaround to activate window: http://superuser.com/questions/327676/application-to-automatically-switch-between-two-applications-in-windows
Tested on Win 10

How to get the name of an External window in C# Application?

i've developed a simple application (.dll) in LABVIEW and i implorted that dll to a C# windows application(Winforms) . Like
[DllImport(#".\sample.dll")]
public static extern void MyFunc(char[] a, StringBuilder b ,Int32 c);
so when i call the function MyFunc a window will be popped up( the Lab View window( Front panel of my labview application
i need to get the window name (ExpectedFuncName) in my C# application. i.e i need to get the name of the external window which is opend by my C# application. Can we use FileVersionInfo or assembly loader to get the name?
Is there any idea to do this?
Thanks in advance.
If you have the window handle, this is relatively easy:
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
[DllImport("user32.dll", SetLastError=true, CharSet=CharSet.Auto)]
static extern int GetWindowTextLength(IntPtr hWnd);
...
int len;
// Window caption
if ((len = GetWindowTextLength(WindowHandle)) > 0) {
sb = new StringBuilder(len + 1);
if (GetWindowText(WindowHandle, sb, sb.Capacity) == 0)
throw new Exception(String.Format("unable to obtain window caption, error code {0}", Marshal.GetLastWin32Error()));
Caption = sb.ToString();
}
Here, 'WindowHandle' is the handle of the created window.
In the case you do not have a window handle (I see you don't), you have to enumerate every desktop top-level window, filter them by the creating process (I see the window is created by you application by calling MyFunc, so you know the process ID [*]), and then use some heuristic to determine the required information.
Here is the C# import of the functions you shall use in the case you do not have the handle:
[DllImport("user32.dll", ExactSpelling = true, SetLastError = true)]
static extern int GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId);
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool EnumWindows(EnumWindowsProc lpEnumFunc, IntPtr lParam);
private delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
Basically EnumWindows calls EnumWindowsProc for each window found in the current desktop. So you can get the window caption.
List<string> WindowLabels = new List<string>();
string GetWindowCaption(IntPtr hWnd) { ... }
bool MyEnumWindowsProc(IntPtr hWnd, IntPtr lParam) {
int pid;
GetWindowThreadProcessId(hWnd, out pid);
if (pid == Process.GetCurrentProcess().Id) {
// Window created by this process -- Starts heuristic
string caption = GetWindowCaption(hWnd);
if (caption != "MyKnownMainWindowCaption") {
WindowLabels.Add(caption);
}
}
return (true);
}
void DetectWindowCaptions() {
EnumWindows(MyEnumWindowsProc, IntPtr.Zero);
foreach (string s in WindowLabels) {
Console.WriteLine(s);
}
}
[*] In the case the window is not created by your application (i.e but from another background process), you shall filter the values returned by GetWindowThreadProcessId using another process ID, but this requires another question...
If you activate LabVIEW scripting (LabVIEW 2010), or install it (LV 8.6, 2009) there is a front-panel property called 'FP.nativewindow'. This returns a handle to the front panel window.
Use the following snippet to get the property:

Get number of apps in TaskBar

I've been wondering how to do this for ages. I'm creating a little app, and I need to figure out how many apps or windows are displayed in the TaskBar.
I've yet to find any info on this at all, I'd appreciate any help at all.
Thank you :)
Here is an article that shows how to get the windows, that are shown when you are using the ALT+TAB key combination.
Basically, you will get the same windows that are shown in the taskbar (unless it is a tool window that is not displayed), but then again, you can always check against WS_EX_TOOLWINDOW (not shown) and WS_EX_APPWINDOW (shown).
You may have a look at my previous answer here; the main difference here is that you just have to count the windows that match the given requirements.
As other's have said you need to enumerate through the windows using the Win32 EnumWindows function, and get your count that way.
You can also enumerate through processes using Process.GetProcesses(); However windows like explorer windows which are not a separate process will not show up in that list.
int appCount = 0;
public bool EnumerateWindows(IntPtr hwnd, IntPtr lParam)
{
if (IsWindowVisible(hwnd))
{
StringBuilder sb = new StringBuilder();
string text = "";
GetWindowText(hwnd, sb, 1024);
text = sb.ToString();
if (text != string.Empty && text != "Program Manager")
{
appCount++;
}
}
return true;
}
private int GetAppCount()
{
appCount = 0;
EnumWindows(EnumerateWindows, new IntPtr(0));
return appCount;
}
internal delegate bool EnumThreadWindowsCallback(IntPtr hwnd, IntPtr lParam);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
internal static extern bool EnumWindows(EnumThreadWindowsCallback callback, IntPtr lParam);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
internal static extern bool IsWindowVisible(IntPtr hwnd);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
internal static extern int GetWindowText(IntPtr hWnd, [Out, MarshalAs(UnmanagedType.LPTStr)] StringBuilder lpString, int nMaxCount);
As far as I know there is no managed way of accessing the taskbar. Here is a link that describes how to access the taskbar by the Windows API. However, I a quick scan did not show any "number of items" or something similar. Still it might point you in the right direction.

C# - Sending messages to Google Chrome from C# application

I've been searching around, and I haven't found how I would do this from C#.
I was wanting to make it so I could tell Google Chrome to go Forward, Back, Open New Tab, Close Tab, Open New Window, and Close Window from my C# application.
I did something similar with WinAmp using
[DllImport("user32", EntryPoint = "SendMessageA")]
private static extern int SendMessage(int Hwnd, int wMsg, int wParam, int lParam);
and a a few others. But I don't know what message to send or how to find what window to pass it to, or anything.
So could someone show me how I would send those 6 commands to Chrome from C#? thanks
EDIT:
Ok, I'm getting voted down, so maybe I wasn't clear enough, or people are assuming I didn't try to figure this out on my own.
First off, I'm not very good with the whole DllImport stuff. I'm still learning how it all works.
I found how to do the same idea in winamp a few years ago, and I was looking at my code. I made it so I could skip a song, go back, play, pause, and stop winamp from my C# code. I started by importing:
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr FindWindow([MarshalAs(UnmanagedType.LPTStr)] string lpClassName, [MarshalAs(UnmanagedType.LPTStr)] string lpWindowName);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
static extern int SendMessageA(IntPtr hwnd, int wMsg, int wParam, uint lParam);
[DllImport("user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
public static extern int GetWindowText(IntPtr hwnd, string lpString, int cch);
[DllImport("user32", EntryPoint = "FindWindowExA")]
private static extern int FindWindowEx(int hWnd1, int hWnd2, string lpsz1, string lpsz2);
[DllImport("user32", EntryPoint = "SendMessageA")]
private static extern int SendMessage(int Hwnd, int wMsg, int wParam, int lParam);
Then the code I found to use this used these constants for the messages I send.
const int WM_COMMAND = 0x111;
const int WA_NOTHING = 0;
const int WA_PREVTRACK = 40044;
const int WA_PLAY = 40045;
const int WA_PAUSE = 40046;
const int WA_STOP = 40047;
const int WA_NEXTTRACK = 40048;
const int WA_VOLUMEUP = 40058;
const int WA_VOLUMEDOWN = 40059;
const int WINAMP_FFWD5S = 40060;
const int WINAMP_REW5S = 40061;
I would get the hwnd (the program to send the message to) by:
IntPtr hwnd = FindWindow(m_windowName, null);
then I would send a message to that program:
SendMessageA(hwnd, WM_COMMAND, WA_STOP, WA_NOTHING);
I assume that I would do something very similar to this for Google Chrome. but I don't know what some of those values should be, and I googled around trying to find the answer, but I couldn't, which is why I asked here. So my question is how do I get the values for:
m_windowName and WM_COMMAND
and then, the values for the different commands, forward, back, new tab, close tab, new window, close window?
Start your research at http://dev.chromium.org/developers
EDIT: Sending a message to a window is only half of the work. The window has to respond to that message and act accordingly. If that window doesn't know about a message or doesn't care at all you have no chance to control it by sending window messages.
You're looking at an implementation detail on how you remote controlled Winamp. Sending messages is just one way to do it and it's the way the Winamp developers chose. Those messages you're using are user defined messages that have a specific meaning only to Winamp.
What you have to do in the first step is to find out if Chromium supports some kind of remote controlling and what those mechanisms are.
You can get the window name easily using Visual Studio's Spy++ and pressing CTRL+F, then finding chrome. I tried it and got
"Chrome_VistaFrame" for the out window. The actual window with the webpage in is "Chrome_RenderWidgetHostHWND".
As far as WM_COMMAND goes - you'll need to experiment. You'll obviously want to send button clicks (WM_MOUSEDOWN of the top off my head). As the back,forward buttons aren't their own windows, you'll need to figure out how to do this with simulating a mouse click at a certain x,y position so chrome knows what you're doing. Or you could send the keyboard shortcut equivalent for back/forward and so on.
An example I wrote a while ago does this with trillian and winamp: sending messages to windows via c# and winapi
There's also tools out there to macro out this kind of thing already, using a scripting language - autoit is one I've used: autoit.com
Ok, here's what I've got so far... I kinda know what I need to do, but it's just a matter of doing it now...
Here's the window from Spy++, I locked onto the Chrome_RenderWidgetHostHWND and clicked the Back button on my keyboard. Here's what I got:
So here's my assumptions, and I've been playing with this forever now, I just can't figure out the values.
IntPtr hWnd = FindWindow("Chrome_RenderWidgetHostHWND", null);
SendMessage(hWnd, WM_KEYDOWN, VK_BROWSER_BACK, 0);
SendMessage(hWnd, WM_KEYUP, VK_BROWSER_BACK, 0);
Now, I just don't know what I should make the WM_KEYDOWN/UP values or the VK_BROWSER_BACK/FORWARD values...
I tried this:
const int WM_KEYDOWN = 0x100;
const int WM_KEYUP = 0x101;
const int VK_BROWSER_BACK = 0x6A;
const int VK_BROWSER_FORWARD = 0x69;
The latter two values I got from the image I just showed, the ScanCodes for those two keys. I don't know if I did it right though. The former two values I got after searching google for the WM_KEYDOWN value, and someone used &H100 and &H101 for the two values. I've tried several other random ideas I've seen floating around. I just can't figure this out.
Oh, and here's the SendMessage method
[DllImport("user32.dll", CharSet = CharSet.Auto)]
static extern int SendMessage(IntPtr hwnd, int wMsg, int wParam, uint lParam);
This is a great site for interop constants:
pinvoke
Another way of finding the values is to search koders.com, using C# as the language, for WM_KEYDOWN or the constant you're after:
Koders.com search
&H values look like that's from VB(6). pinvoke and koders both return results for VK_BROWSER_FORWARD,
private const UInt32 WM_KEYDOWN = 0x0100;
private const UInt32 WM_KEYUP = 0x0101;
public const ushort VK_BROWSER_BACK = 0xA6;
public const ushort VK_BROWSER_FORWARD = 0xA7;
public const ushort VK_BROWSER_REFRESH = 0xA8;
public const ushort VK_BROWSER_STOP = 0xA9;
public const ushort VK_BROWSER_SEARCH = 0xAA;
public const ushort VK_BROWSER_FAVORITES = 0xAB;
public const ushort VK_BROWSER_HOME = 0xAC;
(It's funny how many wrong defintions of VK constants are floating about, considering VK_* are 1 byte 0-255 values, and people have made them uints).
Looks slightly different from your consts. I think the function you're after is SendInput (but I haven't tried it) as it's a virtual key.
[DllImport("User32.dll")]
private static extern uint SendInput(uint numberOfInputs, [MarshalAs(UnmanagedType.LPArray, SizeConst = 1)] KEYBOARD_INPUT[] input, int structSize);
Explanation about the parameters:
Parameters
nInputs- Number of structures in the pInputs array.
pInputs - Pointer to an array of INPUT structures. Each structure represents an event to be inserted into the keyboard or mouse input stream.
cbSize - Specifies the size, in bytes, of an INPUT structure. If cbSize is not the size of an INPUT structure, the function fails.
This needs a KEYBOARD_INPUT type:
[StructLayout(LayoutKind.Sequential)]
public struct KEYBOARD_INPUT
{
public uint type;
public ushort vk;
public ushort scanCode;
public uint flags;
public uint time;
public uint extrainfo;
public uint padding1;
public uint padding2;
}
And finally a sample, which I haven't tested if it works:
/*
typedef struct tagKEYBDINPUT {
WORD wVk;
WORD wScan;
DWORD dwFlags;
DWORD time;
ULONG_PTR dwExtraInfo;
} KEYBDINPUT, *PKEYBDINPUT;
*/
public static void sendKey(int scanCode, bool press)
{
KEYBOARD_INPUT[] input = new KEYBOARD_INPUT[1];
input[0] = new KEYBOARD_INPUT();
input[0].type = INPUT_KEYBOARD;
input[0].vk = VK_BROWSER_BACK;
uint result = SendInput(1, input, Marshal.SizeOf(input[0]));
}
Also you'll need to focus the Chrome window using SetForegroundWindow

Categories

Resources