How to check if an App is running in BlueStacks - c#

I'm wondering how could I check if an app is running inside the BlueStacks Application which simulates Android apps.
In my code, I'm using this line below to start the app, but how can I check if its already running? Note: The check function must work even tho the app has not been initialized by the code-line below. Lets suppose I started manually the app on bluestacks and then I request the check function
System.Diagnostics.Process.Start("C:/Program Files (x86)/BlueStacks/HD-RunApp.exe", "-p com.supercell.clashofclans -a com.supercell.clashofclans.GameApp");
The application mentioned as an example: Clash of Clans
At task manager, the process HD-Frontend.exe is shown whether im using the app i started or not. Which means i cannot use the process name to check if its running because it wont work properly.
private bool appRunning()
{
var runningProcessByName = Process.GetProcessesByName("HD-Frontend");
if (runningProcessByName.Length == 0)
return true;
else
return false;
}

Related

Type.GetTypeFromProgID(string) doesnt work on other machine

private bool StartSkript(string Systemskript)
{
Type typeFromProgID = Type.GetTypeFromProgID("xxx.application"); // this line works on windows 10 and doesnt work on windows server 2019.
if (typeFromProgID == null)
{
return false;
}
try
{
dynamic applicationInstance = Activator.CreateInstance(typeFromProgID);
applicationInstance.RunFormSkript(Systemskript, 0);
return true;
}
catch (Exception)
{
return false;
}
}
Hello,
we are trying to call a function in a running process. The above code finds xxx.application on the dev-machine with no trouble, but in the terminal server test-environment it returns null.
The app xxx is running under the same user as the c# program.
Our first problem is, that we dont really understand why we search for xxx.application (seems to be a class) instead of xxx.exe which would be the processes name.
Next, we dont know how to approach this. How do I check, if I am even looking for the right call "xxx.application"?
ProgID means the ProgramID of a COM-Server. Which is usually registered in the Windows registry after the component was installed.
This is kind of a code to indirectly create an instance of a COM class.
Its kind of an old technique that was heavily used in the 90ties and early 2000 years. ActiveX-Components are based on the COM technology.
Seems the COM-Server with ProgID "xxx.application" is not installed on the terminal server. Or not properly registered. Or your code hasn't enough privileges to read the relevant registry keys etc....

Windows process launch fails silently - can't launch Bluetooth settings in certain scenario

Even though there are command-line commands to start (most of?) the various Control Panel screens in Windows 10, a specific scenario seems to fail:
If the machine starts with Bluetooth turned off (not disabled), running the command which should open the Bluetooth settings screen, simply does nothing. The command could be either ms-settings:bluetooth, bthprops.cpl or ms-settings:Bluetooth.
I've also tried to directly launch the Bluetooth Devices screen (using the command %windir%\explorer.exe shell:::{28803F59-3A75-4058-995F-4EE5503B023C} as described here), but clicking on the "Bluetooth settings" in this window does nothing as well.
The only way to get directly to the Bluetooth settings screen without going through the main Control Panel window and without turning on Bluetooth first, is by right clicking on the relevant tile in Windows Action Center:
Although this seems like a bug on the operating system level, I was wondering if there's any way to know when the launch fails from within C# code. So I've tried using the following code:
try
{
var process = new Process();
process.StartInfo.FileName = "control";
process.StartInfo.Arguments = "bthprops.cpl";
process.Exited += (s, e) =>
{
if (process.ExitCode != 0)
{
TurnOnBt();
}
};
var res = process.Start();
if (!res)
{
TurnOnBt();
}
}
catch (System.Exception ex)
{
int test = 6; // just for breakpoint
}
Problem is, no exception was ever thrown, and most of the time the Process.Exit event was never called.
Further more, calling Windows.Devices.Radios.Radio.GetRadiosAsync() returns an empty list!
Currently the only solution I've found is to manually turn on Bluetooth - it wouldn't change the Process.Start/Exit behavior, but it does allow to successfully lunch the command to directly open Bluetooth Settings window, and to get the list of the machine's Bluetooth/Radio devices. Still, when turning off Bluetooth and restarting the machine, same problem would happen all over again.
Any ideas for a code-based workaround?
note - all this based only on my debugging research, nothing from this is documented
i look how BT-settings window is open via Action Center (win8.1, win 10):
the IApplicationActivationManager interface created and called ActivateApplication method with:
appUserModelId = L"windows.immersivecontrolpanel_cw5n1h2txyewy!microsoft.windows.immersivecontrolpanel"
arguments = L"page=SettingsPagePCSystemBluetooth"
code on c++ can be look like:
if (0 <= CoInitialize(0))
{
IApplicationActivationManager* pAppAct;
if (0 <= CoCreateInstance(__uuidof(ApplicationActivationManager), 0, CLSCTX_ALL, IID_PPV_ARGS(&pAppAct)))
{
ULONG dwProcessId;
pAppAct->ActivateApplication(
L"windows.immersivecontrolpanel_cw5n1h2txyewy!microsoft.windows.immersivecontrolpanel",
L"page=SettingsPagePCSystemBluetooth",
AO_NONE ,
&dwProcessId);
pAppAct->Release();
}
CoUninitialize();
}
the processId (if all ok) reference to "X:\Windows\ImmersiveControlPanel\SystemSettings.exe" -ServerName:microsoft.windows.immersivecontrolpanel
for c# - look IApplicationActivationManager::ActivateApplication in C#?
the "windows.immersivecontrolpanel_cw5n1h2txyewy!microsoft.windows.immersivecontrolpanel" and "page=SettingsPagePCSystemBluetooth" strings not documented anywhere and I not sure are it is "persist" - but currently it used to open manage Bluetooth page in system settings. as is.
in case we run control.exe bthprops.cpl - the process ( control.exe ) launched without any error - as result you and not got any errors when you call this code.
then control.exe bthprops.cpl exec new process rundll32.exe Shell32.dll,Control_RunDLL bthprops.cpl, and exit
the rundll32.dll call Control_RunDLLW(HWND_DESKTOP, (HINSTANCE)&__ImageBase, L"bthprops.cpl", SW_SHOWDEFAULT);
we can and direct call void WINAPI Control_RunDLLW(HWND hwndParent, HINSTANCE hInst, PCWSTR cplName, int nCmdShow ); this api exported from shell32.dll
internally Control_RunDLLW load "bthprops.cpl" (3-rd argument - cplName), find CPlApplet entry point, and send CPL_INIT message. the bthprops.cpl on this message check are bthserv is running via OpenService(L"BTHSERV", ) + QueryServiceStatus (in function BthpIsbluetoothServiceRunning) and if "BTHSERV" not running - it return zero (fail code)

C# monitor external process state

I am making a launcher app in C# on windows. However the process isn't directly started by my C# application but it uses a url to start it e.g "steam://rungameid/xxxxxxx"
I need it to monitor a process by name (say XYZ.exe) in the following fashion:
Receive an event when XYZ.exe starts
Receive an event when XYZ.exe exits
I just want to minimise and restore the my C# application's form when the application is running and not running respectively
thanks
Make a timer (with your preferred timer method) and poll every 'n' milliseconds (find what's best for you... I'd say for minimizing/restoring from a game, 500 milliseconds could be a good start, but experiment), then you can use something like:
bool processRunning = false;
void timerTickMethod()
{
var procIsRunning = Process.GetProcessesByName("xyz.exe").Any();
if(procIsRunning && !processRunning)
ProcessIsStartedEvent(); // or directly minimize your app
else if(!procIsRuning && processRunning)
ProcessIsEndedEvent(); // or directly restore your app
processRunning = procIsRunning;
}
If you want to make sure it's your xyz.exe that is running, you can pass in the full path to GetProcessesByName (so that if there's other xyz.exe in your system, it won't confuse your app)
Update
I was writing from memory, so maybe GetProcessesByName only work for friendly names (with no exe, or path).
If that's the case (I haven't tried), and you need the full path you could do it like:
var procIsRunning = Process.GetProcesses().Any(x => x.MainModule.Filename == #"c:\your\full\path.exe");

Restore a Minimized Windows Mobile Application Form from c++

I have a Compact .Net 2.0 Application (Targeting Windows Mobile 2003 and Above) that has a button to Minimize the Form. I use P/Invoke to Minimize the form/application
//[DllImport("coredll.dll")]
ShowWindow(this.Handle /* Handle for the Form */, SW_MINIMIZED /*6*/)
I have another simple program Splash.exe written in C++ that starts the compact.net application. The purpose of the Splash program is to check if the .Net Application is running and either Restore the .Net Form if running or Start the .Net application if not.
I use the following procedure to check if the .Net application is running:
HWND GetProcessIfAlive(TCHAR szExeName[MAX_PATH]) /* Exe name of the .Net App */
{
HANDLE hSnapShot = NULL;
PROCESSENTRY32 pEntry = {0};
// Get the snapshot of the system
hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPALL, NULL);
pEntry.dwSize = sizeof(pEntry);
//Get first process
Process32First(hSnapShot, &pEntry);
//Iterate thru all processes
while(TRUE)
{
TCHAR *strTempExe = pEntry.szExeFile;
if(_tcscmp(strTempExe, szExeName) == 0)
{
DWORD ProcesID = pEntry.th32ProcessID;
return (HWND)OpenProcess (PROCESS_ALL_ACCESS, FALSE, ProcesID);
//return (HWND)ProcesID;
}
if(!Process32Next (hSnapShot, &pEntry)/* == FALSE*/)
{
return NULL;
}
}
return NULL;
}
After returning from this procedure, I try to restore the Form using
HWND hExistingHandle = GetProcessIfAlive(TEXT("CompactDotNetApp.exe"));
if(hExistingHandle != NULL)
{
if(ShowWindow(hExistingHandle, SW_RESTORE) == FALSE)
{
DWORD err = GetLastError();
}
}
I am getting error 1400 ERROR_INVALID_WINDOW_HANDLE
How can I fix the code the get the proper window Handle for the running Compact .Net Application?
Thanks in Advance.
You're trying to use ShowWindow on a process handle, not a Window handle, which is invalid. You would need the handle to your main app window, which you could get with FindWindow calls, but it's a kludge.
A better approach here is a 2-part solution.
First use a named mutex. Create the mutex when the managed app starts and release it when you exit. The C app can then just check to see if the mutex exists to determine if the app is running or not - no toolhelp work needed.
The second part of the solution is to have your managed app launch a thread (or a timer) to periodically check for a named system event. If it finds that the event is set, it then maximizes the main form and brings it fore.
Back in the C app, if the mutex is found to exist (the app is running) then you simply set the event and exit. That will trigger the thread in the manged app to bring itself to the fore.

Why do I get an InteropServices.COMException when attempting to launch QTP from C#?

This question is a follow-up to the one at Can I use a language other than VBScript to programmatically execute QTP Tests?. I have a C# (.Net 2.0) program which creates an instance of QuickTest.Application and launches QuickTest Professional (version 10.0). All my development testing worked well.
This morning, I attempted to execute the program from a test machine without the development environment (SharpDevelop 2.2.1). I received an error attempting to execute the program when I double-clicked the Windows icon. The console window flashed too quickly to see what it was, so I dropped down to a command prompt and executed the program from there. Everything worked fine. On the second attempted program launch, and all subsequent ones, I receive a System.Runtime.InteropServices.COMException which seems to be caused by the COM object throwing an RPC_E_SERVERFAULT. The function in question is
virtual public QuickTest.Application LaunchQuickTestPro()
{
QuickTest.Application qtpApp = new QuickTest.Application();
qtpApp.Launch();
qtpApp.Visible = false;
return qtpApp;
}
and the qtpApp.Launch(); line is throwing the exception.
I'm at a complete loss as to what could be wrong. It works fine on the dev machine and worked fine once on the test machine. Rebooting between attempts seems to do no good. I'm fairly new to C#, .NET, and COM, so was hoping someone more experienced here might have seen this before. I'm probably missing something simple.
UPDATE: I have discovered this morning, after a reboot, that the Debug build works fine on the test machine (no development environment), but the Release build does not. I am going to try rebuilding and redeploying. Anyone have a suggestion for build options to examine for the Release build?
UPDATE2: It appears that both releases (Debug and Release) work correctly after a fresh reboot. If I try and launch either a second time, I get the error. I've added part of my Main() method and my ExitQTP() method below.
I'm wondering if part of the problem is my misunderstanding how ref should be used. However, the code does work every time when run in the IDE (SharpDevelop 2.2.1).
It does appear that something is not being properly cleaned up after the first run, but I don't know what. Looking at the task monitor, the QTP* processes go away as I expect them to. I think there may be a third process that is causing the problem, but haven't been able to isolate what that is,
//Program starts here
[STAThread]
public static void Main(string[] args)
{
string configFileName =
ConfigurationManager.AppSettings.Get("TestPathsConfigFile");
TextReader configFile = new StreamReader(configFileName);
QTPLauncher launcher = new QTPLauncher();
string testName = null;
try
{
Debug.WriteLine("Creating QuickTest.Application object...");
QuickTest.Application qtpApp = launcher.LaunchQuickTestPro();
Debug.WriteLine("Successfully created QuickTest.Application object...");
while((testName = configFile.ReadLine()) != null)
{
if((testName != string.Empty) &&
(!(testName.TrimStart()).StartsWith(COMMENT_START)))
{
Debug.WriteLine(testName);
launcher.ExecuteQTPTest(testName, ref qtpApp);
}
}
configFile.Close();
... //code unrelated to problem removed.
configFile = null;
launcher.ExitQTP(ref qtpApp);
}
catch(System.Runtime.InteropServices.COMException ce)
{
Console.Error.WriteLine(ce.StackTrace);
}
}
//Exits QTP
virtual public void ExitQTP(ref QuickTest.Application qtpApp)
{
qtpApp.Quit();
qtpApp = null;
}
I suspect the issue is that you are not properly closing (quitting) your QT app instance (if you check your task manager you may see it running) so the subsequent runs fail to initialize properly.
There is a decent blog post where Grant Holliday automates QT for running under Team Build. Many of the same principles would apply.
http://ozgrant.com/2008/02/28/running-hp-quicktest-professional-ui-tests-with-team-build/
If that's not the issue you'll need to provide more details about what you do with the QT application object.
Use the following:
Object oQTPapp;
oQTPapp = Server.CreateObject("QuickTest.Application");
Application qtpApp = (Application) oQTPapp;
Hopefully it will resolve your problem.

Categories

Resources