Windows Mobile 5 - How to kill other application? - c#

currently I’m creating 2 applications (app A and B) for Windows Mobile 5.0 and using Compact Framework 2.0. App A is the main application and B is the sub application.
Below is the flow:
Start app A.
App A will start app B.
App B will do some process.
App B will kill app A.
App B will patch/upgrade app A. (ala update manager)
App B will restart app A.
App B will exit.
Now I’m stuck in killing app A. I did tried using OpenNETCF ProcessEntry Kill() function. When calling Kill(), it made the device crash.
I did tried using the SendMessage(hWnd, WM_CLOSE, 0, 0) funct where WM_CLOSE will have the ProcessEntry.ProcessID value and I didn’t assigned any value to hWnd variable. But it didn’t terminate app A. Did I assign the wrong value?
I also did tried using
Process.GetProcessById(processEntry.ProcessID).CloseMainWindow()
, but failed as GetProcessById only accepts int32 value. Note that processEntry.ProcessID value is larger than int32 value and GetProcessByName() is not supported in Compact Framework.
Could you help me in killing app A through app B?
Thanks.

You may try native code, using the TerminateProcess function:
processHandle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, Pid);
success = TerminateProcess(processHandle, 0);
The above code is from a Task Manager at Code Project.
However if you are writing the code for both the applications, it will be better if you designed a communication mechanism between the two applications. In this way you will send a message from app B to app A and app A will kill itself.

Stormenet, I hardcoded the application's name. Then I generate an object to get all the available process using OpenNETCF.ToolHelp.ProcessEntry[ ] = ProcessEntry.GetProcesses();
then in a foreach loop, if the ProcessEntry object eg: processEntry.ExeFile matches with the "applicationName", i shall use processEntry.Kill().
I think you can get the OpenNETCF.ToolHelp dll from the OpenNETCF site.

Note that if the application you are trying to kill is holding open ports or other system resources then it might hang on exiting. Ensure everything is effectively disposed when the form closes.
This can be acheived by putting stuff in the:
public void Dispose(bool disposing)
{
}
block of code in the designer of your main form, or if you've chosen a less Windows Form centric architecture then just run your dispose calls following Application.Run(new YourForm()) and it will execute after the application has closed.
If you're feeling really lazy then just setup some destructors (otherwise known as finalizers ~) but be careful about navigating through relationships between managed objects at "destruct" time if you do this as there is no guarantee as to which order objects will be destroyed.

ctacke, I think app A crashes due to some of the running threads are not closed properly or still running at the background as app A will run multiple threads during app B executing the Kill( ) function.
If I use the SendMessage(hWnd, WM_CLOSE, 0, 0) function, it will not crash the device (which is a good thing)... it only closes the form. (app A contains multiple forms eg: frmLogin and frmMainMenu). hmmm maybe I need to point hWnd to the right form...

Now I'm taking a different route.
After downloading the patch and put it in a temp folder, I'll do a soft reset using OpenNETCF.WindowsCE.PowerManagement.SoftReset().
App B will be launched upon startup, then it will scan the temp folder and replace app A with the new version.

Related

UWP How to get PID for app triggred using Launcher?

In my UWP app I use Launcher to open a file(for instance txt) by default app.
bool isFileOpen = await Windows.System.Launcher.LaunchFileAsync(storageFile);
Above method uses default app (for instance notepad.exe) to open a file (for instance txt). Once app gets launched, the new process is created. I would like to know PID and Status of that Process. Why? I want to monitor it's Status to determine if the app (like notepad.exe which opened the file) gets closed.
Is any solution to get those infos like showed in Task Manager?
The LaunchFileAsync method just tells the operating system (OS) to start the default app associated with the specified file. It doesn't know about nor return any PID or other information about the process that eventually gets started by the OS.
So I am afraid you can't get this information without looking at all processes and somehow trying to figure out which ones that were started as a result of your app calling the LaunchFileAsync method. You might for example get all running processes just before you call the method, and then again immediately afterwards. But the API itself doesn't return anything useful in regards to this.

Receiving either WM_QueryEndSession or WM_WTSSESSIONCHANGE in WinPE10 in C#

My apologies if this question has been asked and already answered, I have spent the best part of three days experimenting with WndProc() in WinPE (for Windows 10).
How do I "Catch" Messages through WndProc() (or a Handler Routine) in WinPE (Windows 10)?
I have a custom application(written in C# .Net 4.5.2) that is launched by WinPEShl.exe, on boot of WinPE. This is currently an Application that provides access to other applications to enable Windows deployment or Image Capture.
While this Application may not always be the current Windows Form, there a one or two routines that need to be completed before Windows PE has shutdown. I would like this to happen on either the WM_QUERYENDSESSION/WM_ENDSESSION or WTS_SESSION_CHANGE notifications through the overriden WndProc() function.
Currently this is my WndProc() function:
[System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]
protected override void WndProc(ref Message m)
{
// Listen for operating system messages.
if (m.Msg == WM_QUERYENDSESSION)
{
Program.WriteLogFile(4, 1, "WM_QUERYENDSISSION: received. Return Bool=True");
}
if (m.Msg == WTS.WM_WTSSESSION_CHANGE)
{
int wValue = m.WParam.ToInt32();
if (wValue == WTS.WTS_SESSION_LOGOFF)
{
//Write my darn Log file!
Program.WriteLogFile(4, 1, "WM_WTS_SESSION_LOGOFF: received. Return Bool=True");
}
if (wValue == WTS.WTS_CONSOLE_DISCONNECT)
{
Program.WriteLogFile(4, 1, "WM_WTS_SESSION_DISCONNECT: received. Return Bool=True");
}
}
base.WndProc(ref m);
}
Program.WriteLogFile() is a Log File writer (as it says!) that will be used to report that the system is shutting down.
From this Link I am aware that as WinPE is a Stream lined version of Windows, with only a small number of API's being available for usage. I have looked through both of the MinCore.lib sets for both Windows API Sets mentioned - resulting in nill success for finding any function in relation to the WndProc() holder function. I have evensearched OneCore.lib aswell.
I did however find the WTSRegiSessionNotifications() functions. Again even though they register fine in WinPE, my Shell App doesn't receive the messages if another application shuts down the system (such as Windows Setup on completion of the first phase).
Testing in Windows provides both results in the associated application log file.
Should I be using a hidden console app, to capture the CTRL_LOGOFF_EVENT/CTRL-SHUTDOWN_EVENT, or should i be using a service (and have all log writing routed through it)?
Log files from Windows 10 (working as should be) and WinPE available on request.
Thanks for any and all help in this matter.
Kind regards
Richie
I'm not sure why you're not using the regular winforms form lifetime events. I'm guessing you're somewhat more used to C-oriented ways of doing things?
If you've built a winpeshl.ini that starts your program, and it's the only program listed (beyond winpeinit.exe), then when it shuts down, PE shuts down. This is true even if you spawn other applications from your main program (via System.Diagnostics.Process).
So, don't list a lot of programs in winpeshl.ini. Let your one-and-only main program start the rest.
FWIW, I've got a similar app...does image capture, deploy and periodic maintenance. We put our winPE in it's own partition and do a lot of active BCD management to make it boot when we want. I've closed off all the "normal" shutdown routes. Yes, I suppose a persistent user can circumvent...but if they're determined, so be it...but we haven't had an issue with that.

link app with windows service like shut down so that process never end?

link app with windows process so that when user terminated or end the process it says used by another process and also need to insert it into system file like shutdown file using c sharp so that my app never end or terminates
i tried that material but not usefull
this.ShowInTaskbar = false;
I also tried that code in click:
WindowsImpersonationContext ctx = null;
if (!WindowsIdentity.GetCurrent().IsSystem)
{
ctx = WindowsIdentity.Impersonate(System.IntPtr.Zero);
}
string thisuser = WindowsIdentity.GetCurrent().Name;
But have a look at image it is still present in process, what I want is that my process never stops.
what I want is that my process never stops.
To ensure that your process is always running and is started when Windows boots it's easiest to create a windows service instead. It will probably still show up somewhere in task manager and could be killed manually by the user. But windows will try to keep it running.
How to create a service:
https://msdn.microsoft.com/en-us/library/zt39148a(v=vs.110).aspx
And if you need other programs to communicate with your service I find it easy to use a WCF service instead.
https://msdn.microsoft.com/en-us/library/bb386386.aspx

Issue with windows service waiting for a named event, using EventWaitHandle.

I'm currently developing a windows service with c# and .net framework 4.5 to extend the functionality of an existing propietary application, this service blocks on an EventWaitHandleClass (msdn link) waiting for a named event signaled from the main application. Something like this:
bool boolWithFalse = false;
string eName = "notification_event";
string usr = Environment.UserDomainName + "\\" + Environment.UserName;
EventWaitHandleSecurity security = new EventWaitHandleSecurity(); //*
EventWaitHandleAccessRule rule = new EventWaitHandleAccessRule(usr, EventWaitHandleRights.Synchronize, AccessControlType.Allow);
security.AddAccessRule(rule);
EventWaitHandle handle = new EventWaitHandle(false, EventResetMode.ManualReset, eName, out boolWithFalse, security);
//... some non relevant code lines here
//This is where the it locks waiting for the named event
var w = EventWaitHandle.WaitAny(new[] { handle }, Timeout.Infinite);
*: EventWaitHandleSecurity MSDN
Now this works like a charm if i execute my program as a console application, i can easily catch events from the main application and handle them as i intend, BUT, when i install the application as a service it locks waiting for this same named event but never receive the signal. The service is set to run using the NT AUTHORITY\LOCALSERVICE account, i've already tried using my own account (wich the progam uses while running as a console application) and yet nothing happens.
If it helps the application that originates the signal is running under my own account. I appreciate any help as i'm a complete beginner developing desktop applications for windows.
You got lost in the security hoopla. Two problems. The first one is that somebody has to create the event and somebody else has to open it so both components share the same event object. One of them has to use the EventWaitHandle constructor, the other has to call the EventWaitHandle.OpenExisting() method. The normal way is for the service to create the event and for the UI program to open it.
Next problem is the event object visibility. Windows implements namespaces for named operating system objects, pretty similar to how you use namespaces in the C# language. The root namespace is named by the session. And a service runs in a different session than the user's desktop programs. To get the desktop session program to see the event created in the service session, you have to use a "global" event name. Which looks like this:
string eName = "Global\\notification_event";
Do be careful of how you name your globally visible named event. There's another programmer somewhere someday that thinks that "notification_event" is a good choice for a name. You don't want to meet him. A {guid} is a good name, you get one from Tools + Create GUID. It is unique in the known universe, possibly beyond.

create interactive elevated process from windows service and show to logged-on user

I have a service that spawns a WPF application process when a user logs on.
But for some reason the WPF application gets killed about 10 minutes after it has been created? The termination is immediate with no traces found in the Event Log nor are any normal close/exit events called in the WPF application.
In fact, when the termination occurs, Windows 7 seems to hang for a second, the mouse becoming unresponsive and then acting out the mouse gestures after a short delay (when it normalizes, but now lacking the created process).
The When
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
CanHandleSessionChangeEvent = true;
}
protected override void OnSessionChange(SessionChangeDescription changeDescription)
{
if (changeDescription.Reason == SessionChangeReason.SessionLogon
&& changeDescription.SessionId > 0)
{
ApplicationLoader.PROCESS_INFORMATION procInfo;
ApplicationLoader.StartProcessAndBypassUAC(#"myapp.exe", out procInfo);
}
base.OnSessionChange(changeDescription);
}
}
Process Creation As Per Pero Matic Code
// ...
bool result = CreateProcessAsUser(hUserTokenDup, // client's access token
null, // file to execute
applicationName, // command line
ref sa, // pointer to process SECURITY_ATTRIBUTES
ref sa, // pointer to thread SECURITY_ATTRIBUTES
false, // handles are not inheritable
dwCreationFlags, // creation flags
IntPtr.Zero, // pointer to new environment block
null, // name of current directory
ref si, // pointer to STARTUPINFO structure
out procInfo // receives information about new process
);
the termination does not seem to happen if i target notepad.exe, however?
tested it with a vanilla\empty WPF application (.NET 4), and that crashed as well
Process Creation with Administrative Privileges and No Prompt
It seems that the issue is trying to duplicate the administrative SYSTEM token from winlogon.exe (but which is running in session 1+), because if you duplicate the specific user token instead (e.g. from explorer.exe) then the crashes are no more!
this is confirmed with the same vanilla/empty WPF application, and with running Marcel Roma code here - note that he uses explorer.exe instead of winlogon.exe
although using explorer.exe gets rid of the termination I lose the administrative privileges with that, which does not work for me
any ideas how to get it to work with the winlogon process token?
or is it possible to adjust the exlorer.exe token to make the duplicate elevated? im guessing somehow using TokenElevation and SetTokenInformation or AdjustTokenPrivileges
or could it be that Windows 7 has been patched to disallow such process impersonation?
alternatively, is there any way to get the specific user token with administrative privileges (rather than the owner being SYSTEM), but again, without password knowledge/prompts (excluding CreateProcessWithLogonW)
is this maybe to do with garbage collection somehow?
Well I'm just suggesting you a work around:
Why you don't put your core functionalities in a windows service, and then use the wpf app as a frontend ? So that if the user kill it, it doesn't stop the service. Then the service can regularly check that the wpf front end is started, and if needed restart it.
I think it'll be a more "trusted" design that the one you're trying to do, which could let the antivirus think you're a bad software and block you.
And to protect the windows service there is another question here: Protecting a Windows Service from untrusted users
I don't think you can (and definitly should not be able) to do this. Your best bet is to create an application that doesn't need elevated privileges and then use IPC to talk back to your service which then performs administrative tasks on the users behalf.

Categories

Resources