UWP How to get PID for app triggred using Launcher? - c#

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.

Related

Wait for an launched application to stop

We are currently working on a project in UWP where we have to start an external application to modify some documents.
We looked into the Windows.System.Launcher API but it seems that we need more than what it can offer us.
As we launched the application from a file, we use the LaunchFileAsync method, based on the example given by the MSDN :
async void DefaultLaunch()
{
// Path to the file in the app package to launch
string imageFile = #"images\test.png";
var file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(imageFile);
if (file != null)
{
// Launch the retrieved file
var success = await Windows.System.Launcher.LaunchFileAsync(file);
if (success)
{
// File launched
}
else
{
// File launch failed
}
}
else
{
// Could not find file
}
}
So far, the example suit us well but we also need to be warned when the user is done with the file. The best would be to be able to give the launcher a callback method.
We haven't found anything like that yet in the documentation. Is this even possible ? Do we need to use another solution ?
TL;DR : Is there a solution to open another application from a UWP app and wait for it to return a result object ?
If the external app is also a UWP app then Launcher.LaunchUriForResultsAsync is designed for this. It will launch the target app then wait for the app to call back with the results.
See Launch an app for results for a full walkthrough of how this works.
If the target app isn't a UWP app then you can implement the same thing yourself: both apps declare a protocol. The client launches the server with the server's protocol. When the server's done it notifies the caller by launching the client's protocol.
You might also want to look into App Services which allow a UWP server app to expose a REST-like service to clients on the local system. 
The app process isolation model means you can't do this from a UWP app. As you just want to know when an arbitrary program has finished you could write this in traditional .net/win32 and include that in your UWP app via the desktop bridge.

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

Why does Process.Start(string) return null for a WMV file

So I have a WMV video file:
var fileName = #"C:\MyFolder\MyVideo.WMV"
and I am starting the video and getting my Process ID with the code:
var process = Process.Start(fileName);
if (process != null)
{
processId = process.Id;
}
Although my video file starts, process is always null.
From Process.Start(string) MSDN I can see that:
Return Value Type:
System.Diagnostics.Process
A new Process that is
associated with the process resource, or null if no process resource
is started. Note that a new process that’s started alongside already
running instances of the same process will be independent from the
others. In addition, Start may return a non-null Process with its
ProcessHasExited property already set to true. In this case, the
started process may have activated an existing instance of itself and
then exited.
It says that null is returned if no new process is started. But my process is started and null still returned. Why is this?
Because you can't "start a WMV file". In your scenario you rely on the OS file extension handler mappings to invoke a default application to handle it.
UPDATE
From the MSDN docs:
Use this overload to start a process resource by specifying its file
name. The overload associates the resource with a new Process
component. If the process is already running, no additional process
resource is started. Instead, the existing process resource is reused
and no new Process component is created. In such a case, instead of
returning a new Process component, Start returns null to the calling
procedure.
Is it possible that some OS gizmo responsible for directing your media content request to a registered app for an extension was already running? I'd say likely, as logically it would be explorer.exe, which is always up.
UPDATE 2
Here is a screen shot from SysInternals after starting playback of a WMV file using Process.Start:
As you can see wmplayer opens under control of svchost.exe, so at the time you requested the WMV file, svchost was already up, thus Start, returns null as per design. PPT, or rather PowerPoint, will open in a separate process, not under control of svchost.

DLL doesn't store string C#

I have an application that can be launched from the explorer context menu for a Windows drive. When you click the menu item the drive letter is passed to the new instance. I want to make sure that any old instance is closed.
I also want to make sure that the last drive that was selected is persisted, so that when I start the application again from the start-menu, it will remember the drive I originally selected.
It would be best if the already running application would receive an event so that it can update without having to kill and restart.
I tried the following, but that doesn't seem to be working:
This is my Class library method(it is just a line that define a variable so just i have a DLL that there a variable in it and no more)
namespace Dispatch
{
public class cls_get_drive_letter
{
public static string drive_letter;
}
}
This is my loading form code: (Here i will fill the DLL's variable)
private void Frm_loading_Load(object sender, EventArgs e)
{
Dispatch.cls_get_drive_letter.drive_letter = "XXX";
Process currentProcess = Process.GetCurrentProcess();
if (Process.GetProcessesByName(currentProcess.ProcessName, currentProcess.MachineName).Length >1)
{
currentProcess.Kill();
}
}
So when i run this for first time the "XXX" will be stored in DLL but when the current instance of application is running and i am going to run next instance of it the application will be closed because of this code:
Process currentProcess = Process.GetCurrentProcess();
if (Process.GetProcessesByName(currentProcess.ProcessName, currentProcess.MachineName).Length >1)
{
currentProcess.Kill();
}
So when closing code occurs with this code the new "XXX" will not stored in DLL and the last string will be in dll.
All variables, in this case a static field, will only remain the same for the running instance of your application.
When the application is started again the field is empty
A static variable is not stored 'inside a dll' but is stored inside the memory of the application that loads the dll. When a second instance of the application starts, it will have its own memory space and it will have its own version of the string variable. The variable is also not kept between instances, so as soon as you start a new instance it will have its own, empty string variable.
When the application is stopped, the memory for that instance is released and the variable is 'forgotten'.
If you want to share state between applications, there are all kinds of solutions, one could be the System.Configuration.Settings API, a file somewhere, a memory mapped file shared between multiple processes, a Named Pipe, a Kernel Semaphore. Options aplenty.
Until we understand exactly what it is you're trying to accomplish with this shared state, we can't provide you with a better alternative than the explanation that what you're doing right now, will not work do to the way static variables work.
Update based on new information:
You can store your currently selected drive in a Settings file for your project. You can add such file from the project properties in Visual Studio. There's a tab called settings. Create a new setting for "Selected Drive" and make it a User setting (that way you can update it without Admin rights).
To communicate a new drive letter to your already running application, you have a number of options.
For one, you could check whether your executable is already running (like you're doing now) and in that case update the settings file and exit the new instance. Your already running instance could periodically refresh the settings to pick up new values.
When your application starts, you can open a named pipe on your machine on which you listen for drive changes. When the 2nd instance starts, it can detect that the pipe is already there, write the new drive to the pipe and close. The already running application can pick up this message and change its configuration.
You can send a WindowMessage to the other application
You can host a simple WCF service to receive the notification
You can write the new drive letter to a file stored in a known location and have the other instance use a FileSystemWatcher to detect the changes to that file.
As I said the possibilities are endless.
If I were you I'd first make sure that the value is persisted between relaunches by implementing the Settings file in your application. Then investigate the options I described above, do some experimentation and then ask new questions when you cannot figure out how to make it work.

Windows Mobile 5 - How to kill other application?

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.

Categories

Resources