Форум программистов, компьютерный форум, киберфорум
С++ для начинающих
Войти
Регистрация
Восстановить пароль
Карта форума Темы раздела Блоги Сообщество Поиск Заказать работу  
Другие темы раздела
C++ Вычислить номер максимального по модулю элемента массива https://www.cyberforum.ru/ cpp-beginners/ thread374965.html
В одномерном массиве, состоящем из n вещественных элементов, вычислить: - номер максимального по модулю элемента массива; - сумму элементов массива, расположенных после первого положительного элемента. #include "stdafx.h" #include "iostream" #include <stdio.h> #include <math.h> void main() {
Указатели C++
Добрый вечер, не могу что-то разобраться. В первом CASE определяется M, например М="kards\\cherv\\" , вот, а во втором CASE мне нужно к существующему М прибавить еще, например "2.bmp" , чтобы получилось М="kards\\cherv\\2.bmp" как это реализовать??? char* M; char function(int i,int j) { switch (i) { case 0: M="kards\\cherv\\"; break;
C++ Помогите с выводом https://www.cyberforum.ru/ cpp-beginners/ thread374959.html
// Подключение Библиотек #include <iostream.h> #include <stdio.h> #include <math.h> #include <conio.h> #include <string.h> int main()
C++ Не сложные задачи по с++ Всем привет! нужна помощь Найти в массиве минимальный элемент и удалить. https://www.cyberforum.ru/ cpp-beginners/ thread374954.html
scanf() C++
Всем привет! Вот маленький тестовый пример #include <stdio.h> int i; int main() { printf("Enter value: \n");
C++ подскажите по строкам в С++ задание вот такое: Даны две строки, состоящие из слов, разделѐнных одним или несколькими пробелами. Из слов этих строк сформировать новую строку так, чтобы слова в ней чередовались: сначала слово из первой строки, затем через пробел – слово из другой строки и т.д., а в конце поместить слова, оставшиеся без пары. Слова в новой строке должны разделяться ровно одним пробелом. и я написал вот такой... https://www.cyberforum.ru/ cpp-beginners/ thread374946.html
C++ Вычисление значения выражения Как записать вычисление этой суммы? Спасибо. https://www.cyberforum.ru/ cpp-beginners/ thread374936.html Вычислить и вывести на экран в виде таблицы значения функции F на интервале от Х[нач] до Х[кон] с шагом dx. C++
Вычислить и вывести на экран в виде таблицы значения функции F на интервале от Х до Х с шагом dx. -a-(x/10+b) при x<0 и b!=0 (!= это не равно) F= (х-a)/(x-c) при x>0 и b=0 3x+(2/c) в остальных случаях где a,b,c - действительные числа. Функция F должна принимать действительное значение, если выражение
C++ Помогите подправить код Задача. Вводится n-значный массив состоящий из целых элементов. Надо найти произведение четных элементов. Но у меня почему то не работает. Поможете исправить? #include <iostream> #include <time.h> using namespace std; int main() { int n,proz=0; cout << "Введите n: "; //Задаем количество элементов для генерации массива https://www.cyberforum.ru/ cpp-beginners/ thread374902.html C++ Сложение двух матриц Даны две матрицы 2х2: а и е, которые нужно сложить. У меня при сложении в результате выводит только первый столбец, помогите найти ошибку) Вот мой кодпрограммы: cout<<"A+E="<<"\n"; for(int i=0;i<2;i++) { {for(int j=0;j<2;j++) c=a+e; } cout<<c; cout<<"\n\n"; } getch(); https://www.cyberforum.ru/ cpp-beginners/ thread374898.html
C++ Ошибка при наследовании
Имеется архитектура вида: класс "человек", от него производные "препод" и "член приемной комиссии". От их двоих производный класс "Препод и член приемной комиссии". При создании указателя на класс человек и попытки присвоения ему адреса на объект "препод и член приемной комиссии" сообщает что "человек" не является базовым классом для "препод и ЧПК". error C2614: 'TeacherAndChPrKom' : illegal...
C++ Пересечение двух многоугольников Имеются два многоугольника, например два пятиугольника, координаты заданны массивом объектов класса точка. Надо определить, пересекаются ли они? https://www.cyberforum.ru/ cpp-beginners/ thread374888.html
4043 / 2332 / 292
Регистрация: 03.02.2011
Сообщений: 5,066
Записей в блоге: 10
24.11.2011, 01:10 0

Обратиться к файлу, не указывая полный путь к нему - C++ - Ответ 2206141

24.11.2011, 01:10. Показов 4750. Ответов 5
Метки (Все метки)

Ответ

C++
1
WinExec("\"C:\\Program Files\\MyApp.exe\" -L -S", SW_SHOWDEFAULT) // обратите внимание на кавычки, включенные внутрь передаваемой строчки, это достаточно важная штука
UINT WINAPI WinExec
WinExec

Runs the specified application.

Note This function is provided only for compatibility with 16-bit Windows. Applications should use the CreateProcess function.


UINT WINAPI WinExec(
LPCSTR lpCmdLine,
UINT uCmdShow
);

Parameters
lpCmdLine
[in] The command line (file name plus optional parameters) for the application to be executed. If the name of the executable file in the lpCmdLine parameter does not contain a directory path, the system searches for the executable file in this sequence:
The directory from which the application loaded.
The current directory.
The Windows system directory. The GetSystemDirectory function retrieves the path of this directory.
The Windows directory. The GetWindowsDirectory function retrieves the path of this directory.
The directories listed in the PATH environment variable.
uCmdShow
[in] The display options. For a list of the acceptable values, see the description of the nCmdShow parameter of the ShowWindow function.
Return Value
If the function succeeds, the return value is greater than 31.

If the function fails, the return value is one of the following error values.

Return code/value Description

0 The system is out of memory or resources.
ERROR_BAD_FORMAT The .exe file is invalid.
ERROR_FILE_NOT_FOUND The specified file was not found.
ERROR_PATH_NOT_FOUND The specified path was not found.

Remarks
The WinExec function returns when the started process calls the GetMessage function or a time-out limit is reached. To avoid waiting for the time out delay, call the GetMessage function as soon as possible in any process started by a call to WinExec.

Security Remarks

The executable name is treated as the first white space-delimited string in lpCmdLine. If the executable or path name has a space in it, there is a risk that a different executable could be run because of the way the function parses spaces. The following example is dangerous because the function will attempt to run "Program.exe", if it exists, instead of "MyApp.exe".


WinExec("C:\\Program Files\\MyApp", ...)

If a malicious user were to create an application called "Program.exe" on a system, any program that incorrectly calls WinExec using the Program Files directory will run this application instead of the intended application.

To avoid this problem, use CreateProcess rather than WinExec. However, if you must use WinExec for legacy reasons, make sure the application name is enclosed in quotation marks as shown in the example below.


WinExec("\"C:\\Program Files\\MyApp.exe\" -L -S", ...)


Requirements
Client Requires Windows Vista, Windows XP, Windows 2000 Professional, Windows NT Workstation, Windows Me, Windows 98, or Windows 95.
Server Requires Windows Server "Longhorn", Windows Server 2003, Windows 2000 Server, or Windows NT Server.
Header Declared in Winbase.h; include Windows.h.

Library Use Kernel32.lib.

DLL Requires Kernel32.dll.


C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
  STARTUPINFO start_info;
  PROCESS_INFORMATION process_info;
 
  ZeroMemory( &start_info, sizeof(start_info) );
  start_info.cb = sizeof(start_info);
  ZeroMemory( &process_info, sizeof(process_info) );
 
  if ( ! CreateProcess( NULL,              // No module name (use command line)
                         "\"C:\\Великий Могучий Русский Язык\\пример.exe\" ",    // Command line
                         NULL,              // Process handle not inheritable
                         NULL,              // Thread handle not inheritable
                         FALSE,             // Set handle inheritance to FALSE
                         0,                 // No creation flags
                         NULL,              // Use parent's environment block
                         NULL,              // Use parent's starting directory
                         &start_info,       // Pointer to STARTUPINFO structure
                         &process_info ) ){  // Pointer to PROCESS_INFORMATION structure
     ShowMessage("Ошибка доступа по ссылке. Проверьте параметры ссылки.");
      }
BOOL WINAPI CreateProcess
CreateProcess

Creates a new process and its primary thread. The new process runs in the security context of the calling process.

If the calling process is impersonating another user, the new process uses the token for the calling process, not the impersonation token. To run the new process in the security context of the user represented by the impersonation token, use the CreateProcessAsUser or CreateProcessWithLogonW function.


BOOL WINAPI CreateProcess(
LPCTSTR lpApplicationName,
LPTSTR lpCommandLine,
LPSECURITY_ATTRIBUTES lpProcessAttributes,
LPSECURITY_ATTRIBUTES lpThreadAttributes,
BOOL bInheritHandles,
DWORD dwCreationFlags,
LPVOID lpEnvironment,
LPCTSTR lpCurrentDirectory,
LPSTARTUPINFO lpStartupInfo,
LPPROCESS_INFORMATION lpProcessInformation
);

Parameters
lpApplicationName
[in] The name of the module to be executed. This module can be a Windows-based application. It can be some other type of module (for example, MS-DOS or OS/2) if the appropriate subsystem is available on the local computer.
The string can specify the full path and file name of the module to execute or it can specify a partial name. In the case of a partial name, the function uses the current drive and current directory to complete the specification. The function will not use the search path. If the file name does not contain an extension, .exe is assumed. Therefore, if the file name extension is .com, this parameter must include the .com extension.

The lpApplicationName parameter can be NULL. In that case, the module name must be the first white space-delimited token in the lpCommandLine string. If you are using a long file name that contains a space, use quoted strings to indicate where the file name ends and the arguments begin; otherwise, the file name is ambiguous. For example, consider the string "c:\program files\sub dir\program name". This string can be interpreted in a number of ways. The system tries to interpret the possibilities in the following order:


c:\program.exe files\sub dir\program name
c:\program files\sub.exe dir\program name
c:\program files\sub dir\program.exe name
c:\program files\sub dir\program name.exe


If the executable module is a 16-bit application, lpApplicationName should be NULL, and the string pointed to by lpCommandLine should specify the executable module as well as its arguments.

To run a batch file, you must start the command interpreter; set lpApplicationName to cmd.exe and set lpCommandLine to the name of the batch file.

lpCommandLine
[in, out] The command line to be executed. The maximum length of this string is 32K characters.
Windows 2000: The maximum length of this string is MAX_PATH characters.
The Unicode version of this function, CreateProcessW, can modify the contents of this string. Therefore, this parameter cannot be a pointer to read-only memory (such as a const variable or a literal string). If this parameter is a constant string, the function may cause an access violation.

The lpCommandLine parameter can be NULL. In that case, the function uses the string pointed to by lpApplicationName as the command line.

If both lpApplicationName and lpCommandLine are non-NULL, the null-terminated string pointed to by lpApplicationName specifies the module to execute, and the null-terminated string pointed to by lpCommandLine specifies the command line. The new process can use GetCommandLine to retrieve the entire command line. Console processes written in C can use the argc and argv arguments to parse the command line. Because argv[0] is the module name, C programmers generally repeat the module name as the first token in the command line.

If lpApplicationName is NULL, the first white-space – delimited token of the command line specifies the module name. If you are using a long file name that contains a space, use quoted strings to indicate where the file name ends and the arguments begin (see the explanation for the lpApplicationName parameter). If the file name does not contain an extension, .exe is appended. Therefore, if the file name extension is .com, this parameter must include the .com extension. If the file name ends in a period (.) with no extension, or if the file name contains a path, .exe is not appended. If the file name does not contain a directory path, the system searches for the executable file in the following sequence:

The directory from which the application loaded.
The current directory for the parent process.
The 32-bit Windows system directory. Use the GetSystemDirectory function to get the path of this directory.
Windows Me/98/95: The Windows system directory. Use the GetSystemDirectory function to get the path of this directory.
The 16-bit Windows system directory. There is no function that obtains the path of this directory, but it is searched. The name of this directory is System.
The Windows directory. Use the GetWindowsDirectory function to get the path of this directory.
The directories that are listed in the PATH environment variable. Note that this function does not search the per-application path specified by the App Paths registry key. To include this per-application path in the search sequence, use the ShellExecute function.
The system adds a null character to the command line string to separate the file name from the arguments. This divides the original string into two strings for internal processing.

lpProcessAttributes
[in] A pointer to a SECURITY_ATTRIBUTES structure that determines whether the returned handle can be inherited by child processes. If lpProcessAttributes is NULL, the handle cannot be inherited.
The lpSecurityDescriptor member of the structure specifies a security descriptor for the new process. If lpProcessAttributes is NULL or lpSecurityDescriptor is NULL, the process gets a default security descriptor. The ACLs in the default security descriptor for a process come from the primary token of the creator.

Windows XP/2000/NT: The ACLs in the default security descriptor for a process come from the primary or impersonation token of the creator. This behavior changed with Windows XP SP2 and Windows Server 2003.

lpThreadAttributes
[in] A pointer to a SECURITY_ATTRIBUTES structure that determines whether the returned handle can be inherited by child processes. If lpThreadAttributes is NULL, the handle cannot be inherited.
The lpSecurityDescriptor member of the structure specifies a security descriptor for the main thread. If lpThreadAttributes is NULL or lpSecurityDescriptor is NULL, the thread gets a default security descriptor. The ACLs in the default security descriptor for a thread come from the process token.

Windows XP/2000/NT: The ACLs in the default security descriptor for a thread come from the primary or impersonation token of the creator. This behavior changed with Windows XP SP2 and Windows Server 2003.

bInheritHandles
[in] If this parameter TRUE, each inheritable handle in the calling process is inherited by the new process. If the parameter is FALSE, the handles are not inherited. Note that inherited handles have the same value and access rights as the original handles.
dwCreationFlags
[in] The flags that control the priority class and the creation of the process. For a list of values, see Process Creation Flags.
This parameter also controls the new process's priority class, which is used to determine the scheduling priorities of the process's threads. For a list of values, see GetPriorityClass. If none of the priority class flags is specified, the priority class defaults to NORMAL_PRIORITY_CLASS unless the priority class of the creating process is IDLE_PRIORITY_CLASS or BELOW_NORMAL_PRIORITY_CLASS. In this case, the child process receives the default priority class of the calling process.

lpEnvironment
[in] A pointer to the environment block for the new process. If this parameter is NULL, the new process uses the environment of the calling process.
An environment block consists of a null-terminated block of null-terminated strings. Each string is in the form:

name=value

Because the equal sign is used as a separator, it must not be used in the name of an environment variable.

An environment block can contain either Unicode or ANSI characters. If the environment block pointed to by lpEnvironment contains Unicode characters, be sure that dwCreationFlags includes CREATE_UNICODE_ENVIRONMENT. If this parameter is NULL and the environment block of the parent process contains Unicode characters, you must also ensure that dwCreationFlags includes CREATE_UNICODE_ENVIRONMENT.

Note that an ANSI environment block is terminated by two zero bytes: one for the last string, one more to terminate the block. A Unicode environment block is terminated by four zero bytes: two for the last string, two more to terminate the block.

lpCurrentDirectory
[in] The full path to the current directory for the process. The string can also specify a UNC path.
If this parameter is NULL, the new process will have the same current drive and directory as the calling process. (This feature is provided primarily for shells that need to start an application and specify its initial drive and working directory.)

lpStartupInfo
[in] A pointer to a STARTUPINFO or STARTUPINFOEX structure.
To set extended attributes, use a STARTUPINFOEX structure and specify EXTENDED_STARTUPINFO_PRESENT in the dwCreationFlags parameter.

lpProcessInformation
[out] A pointer to a PROCESS_INFORMATION structure that receives identification information about the new process.
Handles in PROCESS_INFORMATION must be closed with CloseHandle when they are no longer needed.

Return Value
If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks
The process is assigned a process identifier. The identifier is valid until the process terminates. It can be used to identify the process, or specified in the OpenProcess function to open a handle to the process. The initial thread in the process is also assigned a thread identifier. It can be specified in the OpenThread function to open a handle to the thread. The identifier is valid until the thread terminates and can be used to uniquely identify the thread within the system. These identifiers are returned in the PROCESS_INFORMATION structure.

The name of the executable in the command line that the operating system provides to a process is not necessarily identical to that in the command line that the calling process gives to the CreateProcess function. The operating system may prepend a fully qualified path to an executable name that is provided without a fully qualified path.

The calling thread can use the WaitForInputIdle function to wait until the new process has finished its initialization and is waiting for user input with no input pending. This can be useful for synchronization between parent and child processes, because CreateProcess returns without waiting for the new process to finish its initialization. For example, the creating process would use WaitForInputIdle before trying to find a window associated with the new process.

The preferred way to shut down a process is by using the ExitProcess function, because this function sends notification of approaching termination to all DLLs attached to the process. Other means of shutting down a process do not notify the attached DLLs. Note that when a thread calls ExitProcess, other threads of the process are terminated without an opportunity to execute any additional code (including the thread termination code of attached DLLs). For more information, see Terminating a Process.

A parent process can directly alter the environment variables of a child process during process creation. This is the only situation when a process can directly change the environment settings of another process. For more information, see Changing Environment Variables.

If an application provides an environment block, the current directory information of the system drives is not automatically propagated to the new process. For example, there is an environment variable named =C: whose value is the current directory on drive C. An application must manually pass the current directory information to the new process. To do so, the application must explicitly create these environment variable strings, sort them alphabetically (because the system uses a sorted environment), and put them into the environment block. Typically, they will go at the front of the environment block, due to the environment block sort order.

One way to obtain the current directory information for a drive X is to make the following call: GetFullPathName("X:", ...). That avoids an application having to scan the environment block. If the full path returned is X:\, there is no need to pass that value on as environment data, since the root directory is the default current directory for drive X of a new process.

When a process is created with CREATE_NEW_PROCESS_GROUP specified, an implicit call to SetConsoleCtrlHandler(NULL,TRUE) is made on behalf of the new process; this means that the new process has CTRL+C disabled. This lets shells handle CTRL+C themselves, and selectively pass that signal on to sub-processes. CTRL+BREAK is not disabled, and may be used to interrupt the process/process group.

Security Remarks

The first parameter, lpApplicationName, can be NULL, in which case the executable name must be in the white space-delimited string pointed to by lpCommandLine. If the executable or path name has a space in it, there is a risk that a different executable could be run because of the way the function parses spaces. The following example is dangerous because the function will attempt to run "Program.exe", if it exists, instead of "MyApp.exe".


LPTSTR szCmdline=_tcsdup(TEXT("C:\\Program Files\\MyApp -L -S"));
CreateProcess(NULL, szCmdline, ...)

If a malicious user were to create an application called "Program.exe" on a system, any program that incorrectly calls CreateProcess using the Program Files directory will run this application instead of the intended application.

To avoid this problem, do not pass NULL for lpApplicationName. If you do pass NULL for lpApplicationName, use quotation marks around the executable path in lpCommandLine, as shown in the example below.


LPTSTR szCmdline[]=_tcsdup(TEXT("\"C:\\Program Files\\MyApp\" -L -S"));
CreateProcess(NULL, szCmdline, ...)


Example Code
For an example, see Creating Processes.

Requirements
Client Requires Windows Vista, Windows XP, Windows 2000 Professional, Windows NT Workstation, Windows Me, Windows 98, or Windows 95.
Server Requires Windows Server "Longhorn", Windows Server 2003, Windows 2000 Server, or Windows NT Server.
Header Declared in Winbase.h; include Windows.h.

Library Use Kernel32.lib.

DLL Requires Kernel32.dll.
Unicode Implemented as CreateProcessW (Unicode) and CreateProcessA (ANSI). Note that Unicode support on Windows Me/98/95 requires Microsoft Layer for Unicode.


C++
1
ShellExecute(NULL, "open", "\"C:\\Великий Могучий Русский Язык\\пример.exe\" ", NULL, NULL, SW_SHOWNORMAL);
HINSTANCE ShellExecute
ShellExecute Function

--------------------------------------------------------------------------------

Performs an operation on a specified file.

Syntax

HINSTANCE ShellExecute( HWND hwnd,
LPCTSTR lpOperation,
LPCTSTR lpFile,
LPCTSTR lpParameters,
LPCTSTR lpDirectory,
INT nShowCmd
);
Parameters

hwnd
[in] Handle to the owner window used for displaying a user interface (UI) or error messages. This value can be NULL if the operation is not associated with a window.
lpOperation
[in] Pointer to a null-terminated string, referred to in this case as a verb, that specifies the action to be performed. The set of available verbs depends on the particular file or folder. Generally, the actions available from an object's shortcut menu are available verbs. The following verbs are commonly used.
edit
Launches an editor and opens the document for editing. If lpFile is not a document file, the function will fail.
explore
Explores the folder specified by lpFile.
find
Initiates a search starting from the specified directory.
open
Opens the file specified by the lpFile parameter. The file can be an executable file, a document file, or a folder.
print
Prints the document file specified by lpFile. If lpFile is not a document file, the function will fail.
NULL
For systems prior to Microsoft Windows 2000, the default verb is used if it is valid and available in the registry. If not, the "open" verb is used.

For Windows 2000 and later systems, the default verb is used if available. If not, the "open" verb is used. If neither verb is available, the system uses the first verb listed in the registry.

lpFile
[in] Pointer to a null-terminated string that specifies the file or object on which to execute the specified verb. To specify a Shell namespace object, pass the fully qualified parse name. Note that not all verbs are supported on all objects. For example, not all document types support the "print" verb.
lpParameters
[in] If the lpFile parameter specifies an executable file, lpParameters is a pointer to a null-terminated string that specifies the parameters to be passed to the application. The format of this string is determined by the verb that is to be invoked. If lpFile specifies a document file, lpParameters should be NULL.
lpDirectory
[in] Pointer to a null-terminated string that specifies the default directory.
nShowCmd
[in] Flags that specify how an application is to be displayed when it is opened. If lpFile specifies a document file, the flag is simply passed to the associated application. It is up to the application to decide how to handle it.
SW_HIDE
Hides the window and activates another window.
SW_MAXIMIZE
Maximizes the specified window.
SW_MINIMIZE
Minimizes the specified window and activates the next top-level window in the z-order.
SW_RESTORE
Activates and displays the window. If the window is minimized or maximized, Windows restores it to its original size and position. An application should specify this flag when restoring a minimized window.
SW_SHOW
Activates the window and displays it in its current size and position.
SW_SHOWDEFAULT
Sets the show state based on the SW_ flag specified in the STARTUPINFO structure passed to the CreateProcess function by the program that started the application. An application should call ShowWindow with this flag to set the initial show state of its main window.
SW_SHOWMAXIMIZED
Activates the window and displays it as a maximized window.
SW_SHOWMINIMIZED
Activates the window and displays it as a minimized window.
SW_SHOWMINNOACTIVE
Displays the window as a minimized window. The active window remains active.
SW_SHOWNA
Displays the window in its current state. The active window remains active.
SW_SHOWNOACTIVATE
Displays a window in its most recent size and position. The active window remains active.
SW_SHOWNORMAL
Activates and displays a window. If the window is minimized or maximized, Windows restores it to its original size and position. An application should specify this flag when displaying the window for the first time.
Return Value

Returns a value greater than 32 if successful, or an error value that is less than or equal to 32 otherwise. The following table lists the error values. The return value is cast as an HINSTANCE for backward compatibility with 16-bit Windows applications. It is not a true HINSTANCE, however. The only thing that can be done with the returned HINSTANCE is to cast it to an int and compare it with the value 32 or one of the error codes below.

0 The operating system is out of memory or resources.
ERROR_FILE_NOT_FOUND The specified file was not found.
ERROR_PATH_NOT_FOUND The specified path was not found.
ERROR_BAD_FORMAT The .exe file is invalid (non-Microsoft Win32 .exe or error in .exe image).
SE_ERR_ACCESSDENIED The operating system denied access to the specified file.
SE_ERR_ASSOCINCOMPLETE The file name association is incomplete or invalid.
SE_ERR_DDEBUSY The Dynamic Data Exchange (DDE) transaction could not be completed because other DDE transactions were being processed.
SE_ERR_DDEFAIL The DDE transaction failed.
SE_ERR_DDETIMEOUT The DDE transaction could not be completed because the request timed out.
SE_ERR_DLLNOTFOUND The specified DLL was not found.
SE_ERR_FNF The specified file was not found.
SE_ERR_NOASSOC There is no application associated with the given file name extension. This error will also be returned if you attempt to print a file that is not printable.
SE_ERR_OOM There was not enough memory to complete the operation.
SE_ERR_PNF The specified path was not found.
SE_ERR_SHARE A sharing violation occurred.


Remarks

This method allows you to execute any commands in a folder's shortcut menu or stored in the registry.

To open a folder, use either of the following calls:

ShellExecute(handle, NULL, <fully_qualified_path_to_folder>, NULL, NULL, SW_SHOWNORMAL);

or

ShellExecute(handle, "open", <fully_qualified_path_to_folder>, NULL, NULL, SW_SHOWNORMAL);

To explore a folder, use:

ShellExecute(handle, "explore", <fully_qualified_path_to_folder>, NULL, NULL, SW_SHOWNORMAL);

To launch the Shell's Find utility for a directory, use:

ShellExecute(handle, "find", <fully_qualified_path_to_folder>, NULL, NULL, 0);

If lpOperation is NULL, the function opens the file specified by lpFile. If lpOperation is "open" or "explore", the function attempts to open or explore the folder.

To obtain information about the application that is launched as a result of calling ShellExecute, use ShellExecuteEx.

Note The Launch folder windows in a separate process setting in Folder Options affects ShellExecute. If that option is disabled (the default setting), ShellExecute uses an open Explorer window rather than launch a new one. If no Explorer window is open, ShellExecute launches a new one.
Windows 95/98/Me: ShellExecute is supported by the Microsoft Layer for Unicode. To use this, you must add certain files to your application, as outlined in Microsoft Layer for Unicode on Windows Me/98/95 Systems.

Function Information

Minimum DLL Version shell32.dll version 3.51 or later
Custom Implementation No
Header shellapi.h
Import library shell32.lib
Minimum operating systems Windows NT 3.1, Windows 95
Unicode Implemented as ANSI and Unicode versions.


In help we trust

Вернуться к обсуждению:
Обратиться к файлу, не указывая полный путь к нему C++
1
Заказать работу у эксперта
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
24.11.2011, 01:10
Готовые ответы и решения:

Полный путь к файлу
Подскажите как вывести в консоли путь к работающему файлу. Вот к этому например: #include...

Полный путь к файлу
подскажите :пишу программу с файлами, но в результате оказывается что его не удается открыть. куда...

Задать полный путь к файлу
Я делаю вот так: string name; ofstream file; cout &lt;&lt; &quot;Введите имя: &quot;; getline(cin,...

Получить полный путь к файлу созданного через ofstream
std::string name = &quot;kalyaka-balyaka&quot;; std::ofstream F(name, std::ios::out); std::cout &lt;&lt; &quot;Polniy...

5
24.11.2011, 01:10
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
24.11.2011, 01:10
Помогаю со студенческими работами здесь

Составить программу которая выводит полный путь к исполняемому файлу этой программы
В билете такой вопрос. Вообще не понимаю где у программы исполняемый файл и что нужно сделать.

По нажатию на кнопку открыть файл в excel (не указывая путь к файлу)
По нажатию на кнопку открыть файл в excel (не указывая путь к файлу)

Открытие файла, используя полный путь к нему
Необходимо открыть текстовый файл для чтения оттуда каких-то данных. Проблема в том, что мне...

Полный путь к файлу
Моя прога выводит в листбокс полный путь к файлу в виде строки private void button1_Click(object...

0
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru