Reputation: 5159
I am creating a file (e.g. myfile.sql) and I want to open the file in the associated application (e.g. SSMS):
Process proc = new Process();
proc.StartInfo.UseShellExecute = true;
proc.StartInfo.FileName = FileName;
proc.StartInfo.WindowStyle = ProcessWindowStyle.Minimized;
proc.Start();
After the process has started I want to evaluate its id. The behavior depends on the state before proc.Start()
. When the application has not been already running the .Id
property contains the id of created process. When the application has been already running the operating system doesn't open new instance but brings the application to the front and application asks whether to reload the file and so on. The problem is that when I consult .Id
at this case I am getting an InvalidOperationException
. WaitForInputIdle
or Handle
behave the same way. Refresh
doesn't improve the situation.
Is it possible to get the id of the process, which was already running without looking for a window with appropriate title (c# Get process window titles)?
As a temporary (?) solution I use:
try
{
return proc.Id;
}
catch
{
return ProcessHelper.GetActiveProcessId();
}
The ProcessHelper is from How do I check if a certain process has focus?
Note: The file is not locked (no reference is held) by the process and even the Process Explorer is not able to find a handle. I is possible to rename or delete the file while is open without any OS protest.
Upvotes: 0
Views: 179