Opening a document programmatically in C++ - c++

I have a console program written in C++. Now I want to open a manual document(in .txt or .pdf) everytime a user of the program types 'manual' in console. How can I do this? Any links to a tutorial would be helpful.Thanks

Try to compile this code (Open.cpp) to Open.exe
Then, you can execute it with (for example) these parameters :
Open "C:\your file.doc"
Open "C:\your file.exe"
Open notepad
#include "windows.h"
int main(int argc, char *argv[])
{
ShellExecute(GetDesktopWindow(), "open", argv[1], NULL, NULL, SW_SHOWNORMAL);
}
Explanation of the program :
You should first include windows
library (windows.h) to get
ShellExecute and GetDesktopWindow function.
ShellExecute is the function to execute the file with parameter
argv[1] that is path to the file to be opened
Another option for lpOperation
arguments instead of "open" is
NULL. "explore" and "find" are
also the options but they are not
for opening a file.
SW_SHOWNORMAL is the constant to
show the program in normal mode (not
minimize or maximize)

Assuming you're on Windows, you're looking for the ShellExecute function. (Use the "open" verb)

In standard, platform independent, C and C++ you can use the system function to pass the name of an application to open your files.
For example, using Windows:
const char text_filename[] = "example.txt";
const char text_application[] = "notepad.exe";
std::string system_str;
system_str = text_application;
system_str += " ";
system_str += text_filename;
// Execute the application
system(system_str.c_str());
The text you send to the system function is platform specific.

In Managed C++ is its very easy
System::Diagnostics::Process::Start(path);
done !

Related

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;
}
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).
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

C++ simple open file dialog in linux

I was wondering if anyone could help me out on implementing a simple file open dialog in C++ in Ubuntu. I am using OpenGL for my GUI, but I would like the user to be able to select a file when the program loads. I have tried gtkmm and wxWidgets but they seem to be too complicated for what I want to do.
If you just need to select a file, then launch a separate program to do that. Like #Dummy00001 said in the comment, you can start zenity --file-selection as a child process and read its stdout.
char filename[1024];
FILE *f = popen("zenity --file-selection", "r");
fgets(filename, 1024, f);
Or you can also write your own program to do the task. That way you can customize the UI as you wish.
I wrote osdialog for this purpose. See osdialog_gtk2.c for an example using GTK+ 2.
This project can help you:
https://github.com/samhocevar/portable-file-dialogs
It uses the same idea described in these answers but it is architecture agnostic and for Unix it wraps zenity, kdialog ...
Here you have more complete code with zenity:
const char zenityP[] = "/usr/bin/zenity";
char Call[2048];
sprintf(Call,"%s --file-selection --modal --title=\"%s\" ", zenityP, "Select file");
FILE *f = popen(Call,"r");
fgets(Bufor, size, f);
int ret=pclose(f);
if(ret<0) perror("file_name_dialog()");
return ret==0;//return true if all is OK

How to get command line of windows "open with .." function?

I previously asked a question that is about how to get windows "open with.." application list.
Here's a link to that question.
We can use SHAssocEnumHandlers interface to get the file association with specific file extension, ex .png
Then use IAssocHandler and can retrieves the full path and file name of the executable file associated with the file type(.png). ex:['Paint': 'C:\\Windows\\system32\\mspaint.exe', ...]
But I want to get the command line of executing mspaint.exe with a given image.
Like this~ "%systemroot%\system32\mspaint.exe" "%1"
Is there another msdn api could help us to get the "open with.." command?
I think it should have, since windows XP already have this ability.
Use AssocQueryString(..., ASSOCSTR_COMMAND, ...);
Example:
TCHAR commandline[1024];
DWORD size = ARRAYSIZE(commandline);
AssocQueryString(0, ASSOCSTR_COMMAND, _T(".txt"), 0, commandline, &size);
There is the SHOpenWithDialog function.
Link to SHOpenWithDialog on MSDN
However, you can't use this to retrieve the selected program. You can only use it to invoke the "Open With" behaviour and eventually open the file (if OAIF_EXEC is set). If that's all you're interested in, then try it out:
#include <windows.h>
#include <Shlobj.h>
#pragma comment(lib, "Shell32.lib")
int main()
{
OPENASINFO info = { 0 };
info.pcszFile = L"C:\\Temp\\SomeFile.png";
info.pcszClass = NULL;
info.oaifInFlags = OAIF_ALLOW_REGISTRATION | OAIF_EXEC;
SHOpenWithDialog(NULL, &info);
return 0;
}

Open .chm file at specific page/topic using command line arguments

I am attempting to open a .chm file(A windows help file) at a specific page/topic by using a system call in C++.
I can successfully open the .chm file to the start page through the following code, but how can I open a .chm file to a specific page/topic inside the help file?
system("start c:/help/myhelp.chm");
PS: I know system is evil/discouraged but the system part is not really relevant its the command line arguments I pass with the .chm file(that will specify what page I want to open) that I am trying to determine.
Ok the arguments are like so:
system(" /Q /E:ON /C HH.EXE ms-its:myChm.chm::myPageName.htm");
There is an API in the Windows SDK called HtmlHelp in the HtmlHelp.h file. You can call like so:
HtmlHelp(GetDesktopWindow(), L"C:\\helpfile\\::/helptopic.html", HH_DISPLAY_TOPIC, NULL);
The Microsoft Docs - HtmlHelpA function provides more information about the function. HtmlHelp() will normally resolve to HtmlHelpA() or HtmlHelpW() depending on whether Unicode compiler option is set or not.
See as well Microsoft Docs - HTML Help API Overview.
Another option - use ShellExecute. The Microsoft help is not easy to use. This approach is much easier and in line with your question. Here is a quick routine to open a help file and pass an ID number. I have just set up some simple char’s so you can see what is going on:
void DisplayHelpTopic(int Topic)
{
// The .chm file usually has the same name as the application - if you don’t want to hardcode it...
char *CmndLine = GetCommandLine(); // Gets the command the program started with.
char Dir[255];
GetCurrentDirectory (255, Dir);
char str1[75] = "\0"; // Work string
strncat(str1, CmndLine, (strstr(CmndLine, ".exe") - CmndLine)); // Pull out the first parameter in the command line (should be the executable name) w/out the .exe
char AppName[50] = "\0";
strcpy(AppName, strrchr(str1, '\\')); // Get just the name of the executable, keeping the '\' in front for later when it is appended to the directory
char parms[300];
// Build the parameter string which includes the topic number and the fully qualified .chm application name
sprintf(parms,_T("-mapid %d ms-its:%s%s.chm"), Topic, Dir, AppName);
// Shell out, using My Window handle, specifying the Microsoft help utility, hh.exe, as the 'noun' and passing the parameter string we build above
// NOTE: The full command string will look like this:
// hh.exe -mapid 0 ms-its:C:\\Programs\\Application\\HelpFile.chm
HINSTANCE retval = ShellExecute(MyHndl, _T("open"), _T("hh.exe"), parms, NULL, SW_SHOW);
}
The topics are numbered within your .chm file. I set up a #define for each topic so if I had to change the .chm file I could just change the include file to match and not have to worry about searching through the code for hardcoded values.

C++: How to make a my program open a .exe with optional args

I'm having some trouble with a program. My goal is to have it open several .exe files with optional args passed. For example if I wanted to open up a pdf I could type the string below into a cmd window.
// If used in a cmd window it will open up my PDF reader and load MyPDF.pdf file
"c:\Test space\SumatraPDF.exe" "c:\Test space\Sub\MyPDF.pdf"
Here are two tries I used. The first opens the PDF but of course doesn't load the file. The second simply doesn't work.
// Opens the PDF in my program
system("\"C:\\Test space\\SumatraPDF.exe\"");
// Error I get inside of a cmd window is the comment below
// 'C:\Test' is not recognized as an internal or external command, operable program or batch file.
//system("\"C:\\Test space\\SumatraPDF.exe\" \"C:\\Test space\\Sub\\MyPDF.pdf\"");
I'm unsure of the reason why the second one does not work. It could be I'm misunderstanding something about system, or I'm not using delimiters right.
I feel like there is a library out there designed for this rather than creating a long string that uses so many delimiters.
Thanks for any help.
Welcome to Stack Overflow!
The system method works by passing it's argument to cmd /c. So you will need an extra set of quotes around it. See related question posted by sled.
As an alternative to system, take a look at the ShellExecute or ShellExecuteEx Win32 API function. It has more features although it is not as portable.
// ShellExecute needs COM to be initialized
CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
SHELLEXECUTEINFO sei = {0};
sei.cbSize = sizeof(sei);
sei.lpFile = prog; // program like c:\Windows\System32\notepad.exe
sei.lpParameters = args; // program arguments like c:\temp\foo.txt
sei.nShow = SW_NORMAL; // app should be visible and not maximized or minimized
ShellExecuteEx(&sei); // launch program
CoUninitialize();
More information here.