Форум » [x]Harbour » Как запуcкать приложения без использования __Run » Ответить

Как запуcкать приложения без использования __Run

SkyNET: Здравствуйте ! Подскажите пожалуйста, как можно запустить приложение не используя командную строку ?

Ответов - 72, стр: 1 2 3 4 All

gfilatov: SkyNET пишет: как можно запустить приложение С помощью функции ShellExecute() Универсальный пример: function RunExternal( cCmd, cVerb, cFile ) local lRet := .t. #ifdef __CLIPPER__ lRet := SwpRunCmd( cCmd, 0, '', '' ) #endif #ifdef __HARBOUR__ if cVerb <> nil ShellExecute( GetDeskTopWindow(), cVerb, cFile, , , 1 ) else __Run( cCmd ) endif #endif return lRet

Andrey: gfilatov пишет: ShellExecute( GetDeskTopWindow(), cVerb, cFile, , , 1 ) А где взять функцию GetDeskTopWindow() для хХарбора отдельно ? И что за параметр cVerb ? А вообще-то лучше привести примеры вызова этой функции ...

gfilatov: Andrey пишет: где взять эту функцию HB_FUNC( GETDESKTOPWINDOW ) { hb_retnl( (HWND)GetDesktopWindow() ); }


Andrey: Я вообще-то не силен в С и поставил так: #pragma BEGINDUMP // из минигуи #include <windows.h> #include <hbapi.h> #include <shlobj.h> HB_FUNC( GETDESKTOPWINDOW ) { hb_retnl( (HWND)GetDesktopWindow() ); } #pragma ENDDUMP Выдает ошибку : Error E2342 test3.prg 36: Type mismatch in parameter 'lNumber' (wanted 'long', got 'HWND__ *') in function HB_FUN_GETDESKTOPWINDOW *** 1 errors in Compile *** Где править ?

gfilatov: Andrey пишет: Где править ? HB_FUNC( GETDESKTOPWINDOW ) { hb_retnl( (LONG)GetDesktopWindow() ); }

Andrey: Нет функции ShellExecute() в чистом хХарборе ! Пришлось цеплять what32.lib и заработало ... А без этой библы обойтись можно ?

gfilatov: Andrey пишет: Нет функции ShellExecute() HB_FUNC( SHELLEXECUTE ) { hb_retnl( (LONG) ShellExecute( (HWND) hb_parnl( 1 ) , (LPCSTR) hb_parcx( 2 ) , (LPCSTR) hb_parcx( 3 ) , ISNIL(4) ? NULL : (LPCSTR) hb_parcx( 4 ) , (LPCSTR) hb_parcx( 5 ) , hb_parni( 6 ) ) ) ; }

Andrey: Получилось , заработало !!! А где можно посмотреть синтаксис этой функции ? В хелпе по хХарбору нет. Методом проб и смотря здесь на форуме получил для себя образцы: #define SW_SHOWNORMAL 1 - а за что этот параметр отвечает ? ShellExecute(GetDeskTopWindow(), 'open', 'myHelp.Chm' , , , SW_SHOWNORMAL) ShellExecute( GetDeskTopWindow(), "open", "notepad.exe", "test5.prg" , , 1 )

gfilatov: Andrey пишет: где можно посмотреть синтаксис этой функции ? Документация WinAPI 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. For more information about verbs and their availability, see Object Verbs. See Extending Shortcut Menus for further discussion of shortcut menus. 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.

Andrey: Блин, с моим английским буду разбираться долго.... Так бы сразу и сказал, что искать в WinAPI нужно ....

Andrey: Ура, нашел на нашем языке...... Функция ShellExecute модуль ShellAPI Группа ссылок: Диски, Папки и Файлы Описание: function ShellExecute(hWnd: HWND; Operation, FileName, Parameters, Directory: PChar; ShowCmd: Integer): HINST; Функция может открыть или напечатать определенный файл. Исполняет как Windows-приложения так и открывает файлы-документы. Например с файлами типа ".txt" связан Блокнот "Notepad.exe" и запуск файла "my.txt" приведет к тому, что будет запущен Блокнот и в него будет передан параметр с именем файла. Также с помощью этой функци можно в проводнике открыть папку. Параметры: hWnd: Хендл родителя запускаемого приложения. Operation: Строка определяющая команду для исполнения. Может содержать: "open" - открыть файл определенный параметром FileName. "print" - напечатать файл определенный параметром FileName. "explore" - открыть папку определенную параметром FileName. Если параметр Operation равен nil, то по умолчанию выполняется операция "open". FileName: Определяет имя файла или папки для открытия или печати. Функция может запускать файл на исполнение или документ на печать. Parameters: определяет параметры передаваемые при запуске исполняемого приложения. Бессмысленно его использовать при запуске документа. Параметр можеть быть равен Nil. Directory: опеределяет каталог по умолчанию(рабочий каталог). Получить\установить можно с помощью функций GetCurrentDirectory, SetCurrentDirectory. ShowCmd: определяет режим открытия файла. См. константы открытия\показа SW_. Возвращаемые значения Функция возвращает Хендл открытого приложения или сервера DDE. Возвращаемое значение должно быть больше 32. В противном случае это ошибка: 0 - Системе не хватает памяти, выполняемый файл испорчен или нехватает ресурсов. ERROR_FILE_NOT_FOUND - файл не найден. ERROR_PATH_NOT_FOUND - путь не найден. ERROR_BAD_FORMAT - .EXE-Файл неверен (не-Win32.EXE или ошибка в .EXE). SE_ERR_ACCESSDENIED - Операционная Система отвергла доступ к файлу. SE_ERR_ASSOCINCOMPLETE - неправильная или неполная ассоциация с файлом. SE_ERR_DDEBUSY - транзакция DDE не может завершаться поскольку были запущены другие транзакции. SE_ERR_DDEFAIL - транзакция DDE потерпела неудачу. SE_ERR_DDETIMEOUT - транзакция DDE не могла завершаться поскольку запрос несинхронизированный. SE_ERR_DLLNOTFOUND - динамическая библиотека(.DLL) не обнаружена. SE_ERR_FNF - файл не найден. SE_ERR_NOASSOC - нет приложения ассоцированного с данным типом файла. SE_ERR_OOM - недостаточно памяти для завершения операции. SE_ERR_PNF - путь не найден. SE_ERR_SHARE - разделение(shared) файла неверно. См. также: FindExecutable, ShellExecuteEx Функция находится в файле shell32.dll

Andrey: И еще про окна: Константы состояния окна при открытии\показе. Группа ссылок: Окна SW_HIDE - Прячет окно и переводит в активное состояние другое окно. SW_MINIMIZE - Минимизирует окно и активизирует окно верхнего уровня в списке менеджера окон. SW_RESTORE - Действует так же, как и SW_SHOWNORMAL. SW_SHOW - Активизирует окно и выводит его в текущей позиции и текущего размера. SW_SHOWDEFAULT - Активизирует окно и выводит его с использованием текущих умолчаний. SW_SHOWMAXIMIZED - Активизирует окно и выводит его с максимально размером. SW_SHOWMINIMIZED - Активизирует окно и выводит его в виде пиктограммы. SW_SHOWMINNOACTIVATE - Выводит окно как пиктограмму; бывшее активныь в данный момент окно остается активным. SW_SHOWNA - Выводит окно с учетом его состояния в данный момент; активное в данный момент окно остается активным. SW_SHOWNOACTIVATE - Выводит окно в его прежней позиции и прежнего размера; активное в данный момент окно остаета активным. SW_SHOWNORMAL - Активизирует окно и выводит его на экран. Если окно было увеличено или уменьшено до пиктограммы, то система Windows восстановит начальное положение и размер окна. SW_SHOWSMOOTH - Выводит окно так, чтобы оно меньше всего перекрывалось с другими окнами.

Andrey: Спасибо Григорий !!! Кому нужно, привожу пример полностью (на чистом хХарборе): скопировать в файл test4.prg // компилировать без библиотеки what32.lib // ------ смотри #include "winuser.h" /* * ShowWindow() Commands */ #define SW_HIDE 0 #define SW_SHOWNORMAL 1 #define SW_NORMAL 1 #define SW_SHOWMINIMIZED 2 #define SW_SHOWMAXIMIZED 3 #define SW_MAXIMIZE 3 #define SW_SHOWNOACTIVATE 4 #define SW_SHOW 5 #define SW_MINIMIZE 6 #define SW_SHOWMINNOACTIVE 7 #define SW_SHOWNA 8 #define SW_RESTORE 9 #define SW_SHOWDEFAULT 10 #define SW_FORCEMINIMIZE 11 #define SW_MAX 11 FUNCTION MAIN() //ShellExecute(GetDeskTopWindow(), 'open', 'myHelp.Chm' , '', '', SW_SHOWNORMAL) ShellExecute(GetDeskTopWindow(), 'open', "notepad.exe", "test4.prg", '', SW_SHOWMAXIMIZED) ShellExecute(GetDeskTopWindow(), 'explore', CurDrive()+":"+DirName(), , , SW_SHOWNORMAL) RunExternal( "","open","notepad.exe", "test4.prg") wait RETURN NIL /////////////////////////////////////////////////////// function RunExternal( cCmd, cVerb, cFile, cPar4 ) local lRet := .t. #ifdef __CLIPPER__ lRet := SwpRunCmd( cCmd, 0, '', '' ) #endif #ifdef __HARBOUR__ if cVerb <> nil ShellExecute( GetDeskTopWindow(), cVerb, cFile, cPar4 , , 1 ) else __Run( cCmd ) endif #endif return lRet /////////////////////////////////////////////////////////// #pragma BEGINDUMP #include <windows.h> #include <hbapi.h> #include <shlobj.h> HB_FUNC( GETDESKTOPWINDOW ) { hb_retnl( (LONG)GetDesktopWindow() ); } HB_FUNC( SHELLEXECUTE ) { hb_retnl( (LONG) ShellExecute( (HWND) hb_parnl( 1 ) , (LPCSTR) hb_parcx( 2 ) , (LPCSTR) hb_parcx( 3 ) , ISNIL(4) ? NULL : (LPCSTR) hb_parcx( 4 ) , (LPCSTR) hb_parcx( 5 ) , hb_parni( 6 ) ) ) ; } #pragma ENDDUMP

Andrey: А как сделать запуск, если строка запуска слишком длинная ? Типа: C:\ABON\UTIL\AbonentCheck.exe C:\ABON\TEMP\chk4.dbf C:\ABON\TEMP\chk4_frm.dbf C:\ABON\TEMP\tarif.dbf Приходиться делать бат-файл, запускаеть его через ShellExecute(GetDeskTopWindow(), 'open', "C:\ABON\myrun.bat", "", '', SW_HIDE) а потом удалять этот бат-файл. А по другому нельзя ?

Andrey: Спасибо, сам разобрался ..... ShellExecute(GetDeskTopWindow(), 'open', "C:\ABON\UTIL\AbonentCheck.exe", "C:\ABON\TEMP\chk4.dbf C:\ABON\TEMP\chk4_frm.dbf C:\ABON\TEMP\tarif.dbf ", '', SW_HIDE)

Andrey: Проблема с запуском BAT-файла, процесс стартует скрытным и никак не виден на экране !!! Дело в том что я запускаю процесс архивации, а он не виден на экране.... А в Диспечере задач он запускается и потом делает архив.... Как можно исправить ??? // ------ смотри #include "winuser.h" /* * ShowWindow() Commands */ #define SW_HIDE 0 #define SW_SHOWNORMAL 1 #define SW_NORMAL 1 #define SW_SHOWMINIMIZED 2 #define SW_SHOWMAXIMIZED 3 #define SW_MAXIMIZE 3 #define SW_SHOWNOACTIVATE 4 #define SW_SHOW 5 #define SW_MINIMIZE 6 #define SW_SHOWMINNOACTIVE 7 #define SW_SHOWNA 8 #define SW_RESTORE 9 #define SW_SHOWDEFAULT 10 #define SW_FORCEMINIMIZE 11 #define SW_MAX 11 FUNCTION MAIN() LOCAL cFile cFile := CurDrive()+":"+DirName()+"\backup_db.bat" ShellExecute(GetDeskTopWindow(), 'open',cFile, "", "" , , SW_SHOWNORMAL) wait RETURN NIL /////////////////////////////////////////////////////// #pragma BEGINDUMP #include <windows.h> #include <hbapi.h> #include <shlobj.h> HB_FUNC( GETDESKTOPWINDOW ) { hb_retnl( (LONG)GetDesktopWindow() ); } HB_FUNC( SHELLEXECUTE ) { hb_retnl( (LONG) ShellExecute( (HWND) hb_parnl( 1 ) , (LPCSTR) hb_parcx( 2 ) , (LPCSTR) hb_parcx( 3 ) , ISNIL(4) ? NULL : (LPCSTR) hb_parcx( 4 ) , (LPCSTR) hb_parcx( 5 ) , hb_parni( 6 ) ) ) ; } #pragma ENDDUMP Сам backup_db.bat: @echo off U:\UTILI\rar.exe a -m5 -r -dh C:\ARHIV\arx_2008.10.06.rar U:\MyProg\*.* U:\UTILI\rar.exe a -m5 -r -dh C:\ARHIV\arx_2008.10.06.rar C:\MyProg\*.* echo . echo . echo =============== АРХИВИРОВАНИЕ ЗАКОНЧЕНО ============================ echo . echo . echo ===== АРХИВ-БД создан в папке ==== C:\ARHIV\arx_2008.10.06.rar

Loach: Извиняйте, а почему не пользоваться для архивации встроенным в xHarobour зипом (hbzip.lib в контрибах) ? Тогда и с батником проблем не будет.

Andrey: Кроме ZIP'a есть еще вызов батников. А их тогда как вызывать. Это в качестве примера, чтоб разобраться с CMD....

Петр: WAPI функция ShellExecute принимает в качестве аргументов 6 параметров, а вы, что передаете ShellExecute(GetDeskTopWindow(), 'open',cFile, "", "" , , SW_SHOWNORMAL)

Andrey: Семён Семёнович ...... уже склероз !!! Спасибо Петр ! Всегда так бывает, все баги на поверхности лежат .....



полная версия страницы