Cole
Cole

Reputation: 23

Stopping an exe file from being run C++

I am creating an application to manage other applications or exe files on a user's computer, and stop them from accessing them at certain times (like ColdTurkey's application blocking feature).

The way I am trying to do this has not been working so far - I attempted to do this by opening the file dwShareMode set to 0 using the CreateFile function. This seems to work for files such as text files and does not allow the file to be opened, however this is not the case if I try and do this same approach on exe files, and the user is free to open the file.

I assume that exe files are not 'read' in the same way by Windows as a text file is read by notepad and that that means setting the dwShareMode to 0 does not affect it being opened, however I do not know what the difference between these are. Any help would be appreciated.

Code here (for the text file):

#include <windows.h>
#include <string>
#include <iostream>

using namespace std;

int main()
{
    HANDLE test;
    test = CreateFile("test.txt",
         GENERIC_WRITE,
         0,
         NULL,
         CREATE_NEW,
         FILE_ATTRIBUTE_NORMAL,
         NULL);

    cout << "press enter to stop blocking application: ";
    string b;
    getline(cin, b); 
    cout << endl;
    CloseHandle(test);
    return 0;
}

Upvotes: 2

Views: 1144

Answers (2)

A. P. Damien
A. P. Damien

Reputation: 386

Not a windows expert -- I'm used to Unix/Linux and use the Cygwin package so I can program "in Unix" on my Windows desktop -- but it looks to me like you need to set the lpSecurityAttributes parameter, the one that comes after dwShareMode.

I think the following page might be helpful: https://msdn.microsoft.com/en-us/library/windows/desktop/aa364399(v=vs.85).aspx

Upvotes: -1

Greg Hewgill
Greg Hewgill

Reputation: 994021

Your code works fine for me to block execution of the file. You do need to specify OPEN_EXISTING instead of CREATE_NEW (because you're not trying to create a new file here).

Upvotes: 2

Related Questions