I want to close my txt file or chrome using c++ program while they are running . Can we do that by ShellExecute(NULL, "open", "C://File Path" , NULL, NULL, SW_SHOWNORMAL);
or by SendMessage(WM_CLOSE)
.
If yes than how?
Asked
Active
Viewed 441 times
0

πάντα ῥεῖ
- 1
- 13
- 116
- 190
-
2Pretty hard. You don't really know how the file will be opened. In full generality I think this is impossible. – David Heffernan Sep 26 '21 at 14:30
-
I am not sure it's possible using the WinApi. One would need to get the PIDs of the processes holding an open file handle to the txt file. IIRC there are tricks you can get those relations under Linux systems, but not so sure for Windows. – πάντα ῥεῖ Sep 26 '21 at 14:43
-
@πάντα ῥεῖ You can kill the process in Windows, but maybe the user was editing the file, or Chrome had other tabs open. You could instead target individual applications with UI Automation for example, then close the tab or whatever. – Barmak Shemirani Sep 26 '21 at 15:40
-
@πάν PIDs aren't very useful outside of POSIX. [TerminateProcess](https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-terminateprocess) takes a process handle, that [CreateProcess](https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createprocessw) conveniently returns. If you need to find the processes that have opened a file, then [that's supported](https://devblogs.microsoft.com/oldnewthing/20120217-00/?p=8283), too. – IInspectable Sep 26 '21 at 15:55
-
If there are multiple text and chrome, how do you choose? It's really not an easy thing to do. See also, [How to effectively kill a process in C++ (Win32)?](https://stackoverflow.com/questions/1916574/how-to-effectively-kill-a-process-in-c-win32) – Strive Sun Sep 27 '21 at 09:08
1 Answers
1
I suggest you could follow the following steps:
Use EnumProcesses function to get an array of all of the ProcessIDs.
For each ProcessID, use OpenProcess to open and get a handle to each process. Use
PROCESS_QUERY_INFORMATION | PROCESS_TERMINATE
access rights. If the process doesn't open, then you don't have permission to close it, it's probably a system process.If the process has opened successfully, use GetModuleBaseName to get the name of the process.
If the name matches, use TerminateProcess to terminate the process.

Jeaninez - MSFT
- 3,210
- 1
- 5
- 20