Страница: 1 | 2 |
Вопрос: CMD.EXE
Добавлено: 23.08.07 12:15
Автор вопроса: KreAtoR
Ответы
Всего ответов: 23
Номер ответа: 16
Автор ответа:
Mr.Smile
ICQ: 427682013
Вопросов: 14
Ответов: 464
Профиль | | #16
Добавлено: 24.08.07 13:55
2KreAtoR
А ты пробовал
Номер ответа: 17
Автор ответа:
KreAtoR
Вопросов: 120
Ответов: 438
Профиль | | #17
Добавлено: 24.08.07 17:40
чаго то снова ничего не выходит. Снечала висла а теперь вообще непонятно что .
Кидаю код:
frmConsole
Public Console As New clsConsole
Private Sub CommandCloseConsole_Click()
Console.CloseConsole
End Sub
Private Sub CommandOpenConsole_Click()
Console.OpenConsole
End Sub
Private Sub CommandWriteText_Click()
Console.SendText Text.Text
End Sub
basConsole
Option Explicit
Declare Function AllocConsole Lib "kernel32" () As Long
Declare Function FreeConsole Lib "kernel32" () As Long
Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long
Declare Function GetStdHandle Lib "kernel32" (ByVal nStdHandle As Long) As Long
Declare Function WriteConsole Lib "kernel32" Alias "WriteConsoleA" (ByVal hConsoleOutput As Long, lpBuffer As Any, ByVal nNumberOfCharsToWrite As Long, lpNumberOfCharsWritten As Long, lpReserved As Any) As Long
Declare Function SetConsoleCtrlHandler Lib "kernel32" (ByVal HandlerRoutine As Long, ByVal Add As Long) As Long
Public Const STD_OUTPUT_HANDLE = -11&
Public hConsole As Long
Public Function ConsoleHandler(ByVal CtrlType As Long) As Long
ConsoleHandler = 1 'Keep track of the console, it'll survive even Ctrl+Break
End Function
clsConsole
Public Function CloseConsole() As Boolean
If CloseHandle(hConsole) <> 0 Then hConsole = 0
FreeConsole
End Function
Public Function OpenConsole() As Boolean
'We open the Window
If AllocConsole() Then
hConsole = GetStdHandle(STD_OUTPUT_HANDLE)
If hConsole = 0 Then
FreeConsole
Else
SetConsoleCtrlHandler AddressOf ConsoleHandler, True
OpenConsole = True
End If
End If
End Function
Public Function SendText(sText As String) As Boolean
 im sOut As String, cWritten As Long
sOut = sText & vbCrLf
'Write the text to the console
SendText = WriteConsole(hConsole, ByVal sOut, Len(sOut), cWritten, ByVal 0&
End Function
Private Sub Class_Terminate()
'If a console is open then
If hConsole <> 0 Then
'close our handle to it and
CloseHandle hConsole
'disconnect it from the process.
FreeConsole
End If
End Sub
Это API Консоль. Вы меня как убедили, так вот я с ней щас и сижу
Посмотрите плиз может надо что подправить. Хотя это точно надо!!!!!
Номер ответа: 18
Автор ответа:
Millenium
ICQ: 629966
Вопросов: 118
Ответов: 903
Web-сайт:
Профиль | | #18
Добавлено: 26.08.07 01:08
(C) Copyright 1985-2001 Microsoft Corp.
C:\Documents and Settings\Rashid>/?
'/?' is not recognized as an internal or external command,
operable program or batch file.
C:\Documents and Settings\Rashid>help
For more information on a specific command, type HELP command-name
ASSOC  isplays or modifies file extension associations.
AT Schedules commands and programs to run on a computer.
ATTRIB Displays or changes file attributes.
BREAK Sets or clears extended CTRL+C checking.
CACLS  isplays or modifies access control lists (ACLs) of files.
CALL Calls one batch program from another.
CD Displays the name of or changes the current directory.
CHCP Displays or sets the active code page number.
CHDIR  isplays the name of or changes the current directory.
CHKDSK Checks a disk and displays a status report.
CHKNTFS  isplays or modifies the checking of disk at boot time.
CLS Clears the screen.
CMD Starts a new instance of the Windows command interpreter.
COLOR Sets the default console foreground and background colors.
COMP Compares the contents of two files or sets of files.
COMPACT  isplays or alters the compression of files on NTFS partitions.
CONVERT Converts FAT volumes to NTFS. You cannot convert the
current drive.
COPY Copies one or more files to another location.
DATE Displays or sets the date.
DEL  eletes one or more files.
DIR  isplays a list of files and subdirectories in a directory.
DISKCOMP Compares the contents of two floppy disks.
DISKCOPY Copies the contents of one floppy disk to another.
DOSKEY Edits command lines, recalls Windows commands, and creates macros.
ECHO Displays messages, or turns command echoing on or off.
ENDLOCAL Ends localization of environment changes in a batch file.
ERASE  eletes one or more files.
EXIT Quits the CMD.EXE program (command interpreter).
FC Compares two files or sets of files, and displays the differences
between them.
FIND Searches for a text string in a file or files.
FINDSTR Searches for strings in files.
FOR Runs a specified command for each file in a set of files.
FORMAT Formats a disk for use with Windows.
FTYPE  isplays or modifies file types used in file extension associations.
GOTO Directs the Windows command interpreter to a labeled line in a
batch program.
GRAFTABL Enables Windows to display an extended character set in graphics
mode.
HELP Provides Help information for Windows commands.
IF Performs conditional processing in batch programs.
LABEL Creates, changes, or deletes the volume label of a disk.
MD Creates a directory.
MKDIR Creates a directory.
MODE Configures a system device.
MORE Displays output one screen at a time.
MOVE Moves one or more files from one directory to another directory.
PATH Displays or sets a search path for executable files.
PAUSE Suspends processing of a batch file and displays a message.
POPD Restores the previous value of the current directory saved by PUSHD.
PRINT Prints a text file.
PROMPT Changes the Windows command prompt.
PUSHD Saves the current directory then changes it.
RD Removes a directory.
RECOVER Recovers readable information from a bad or defective disk.
REM Records comments (remarks) in batch files or CONFIG.SYS.
REN Renames a file or files.
RENAME Renames a file or files.
REPLACE Replaces files.
RMDIR Removes a directory.
SET  isplays, sets, or removes Windows environment variables.
SETLOCAL Begins localization of environment changes in a batch file.
SHIFT Shifts the position of replaceable parameters in batch files.
SORT Sorts input.
START Starts a separate window to run a specified program or command.
SUBST Associates a path with a drive letter.
TIME Displays or sets the system time.
TITLE Sets the window title for a CMD.EXE session.
TREE Graphically displays the directory structure of a drive or path.
TYPE Displays the contents of a text file.
VER  isplays the Windows version.
VERIFY Tells Windows whether to verify that your files are written
correctly to a disk.
VOL  isplays a disk volume label and serial number.
XCOPY Copies files and directory trees.
C:\Documents and Settings\Rashid>
Номер ответа: 19
Автор ответа:
Millenium
ICQ: 629966
Вопросов: 118
Ответов: 903
Web-сайт:
Профиль | | #19
Добавлено: 26.08.07 01:11
А зачем-бы тебе не юзать сразу РЕГЕДИТ, чем гадится через консоль? Через регедит можеш найти все значения, анутриннеми командами типа КОПИ, ДЕЛ и пр. можеш выполнять операции из ВБ, а напоследок записи опять таки делать через РЕГЕДИТ. То есть функчией записи/чтения...
Поили чтонить? И сам с трудом понял
Номер ответа: 20
Автор ответа:
Mr.Smile
ICQ: 427682013
Вопросов: 14
Ответов: 464
Профиль | | #20
Добавлено: 26.08.07 13:35
2KreAtoR
Консоля твоя работает нормально. Но она не выпоняет функций стандартной Командной строки. Если ты хочешь выводить в ней ответы от консольных приложений (например, ping.exe 127.0.0.1), то можешь использовать этот код:
'Requires two textboxes and one command button.
'Set MultiLine property of Text2 to true.
'
'Original bcx version of this program was made by
' dl <dl@tks.cjb.net>
'VB port was made by Jernej Simoncic <jernej@isg.si>
'Visit Jernejs site at http://www2.arnes.si/~sopjsimo/
'
'Note: don't run plain DOS programs with this example
'under Windows 95,98 and ME, as the program freezes when
'execution of program is finnished.
Option Explicit
Private Declare Function CreatePipe Lib "kernel32" (phReadPipe As Long, phWritePipe As Long, lpPipeAttributes As SECURITY_ATTRIBUTES, ByVal nSize As Long) As Long
Private Declare Sub GetStartupInfo Lib "kernel32" Alias "GetStartupInfoA" (lpStartupInfo As STARTUPINFO)
Private Declare Function CreateProcess Lib "kernel32" Alias "CreateProcessA" (ByVal lpApplicationName As String, ByVal lpCommandLine As String, lpProcessAttributes As Any, lpThreadAttributes As Any, ByVal bInheritHandles As Long, ByVal dwCreationFlags As Long, lpEnvironment As Any, ByVal lpCurrentDriectory As String, lpStartupInfo As STARTUPINFO, lpProcessInformation As PROCESS_INFORMATION) As Long
Private Declare Function SetWindowText Lib "user32" Alias "SetWindowTextA" (ByVal hwnd As Long, ByVal lpString As String) As Long
Private Declare Function ReadFile Lib "kernel32" (ByVal hFile As Long, lpBuffer As Any, ByVal nNumberOfBytesToRead As Long, lpNumberOfBytesRead As Long, lpOverlapped As Any) As Long
Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long
Private Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long
Private Type SECURITY_ATTRIBUTES
nLength As Long
lpSecurityDescriptor As Long
bInheritHandle As Long
End Type
Private Type PROCESS_INFORMATION
hProcess As Long
hThread As Long
dwProcessId As Long
dwThreadId As Long
End Type
Private Type STARTUPINFO
cb As Long
lpReserved As Long
lpDesktop As Long
lpTitle As Long
dwX As Long
dwY As Long
dwXSize As Long
dwYSize As Long
dwXCountChars As Long
dwYCountChars As Long
dwFillAttribute As Long
dwFlags As Long
wShowWindow As Integer
cbReserved2 As Integer
lpReserved2 As Byte
hStdInput As Long
hStdOutput As Long
hStdError As Long
End Type
Private Type OVERLAPPED
ternal As Long
ternalHigh As Long
offset As Long
OffsetHigh As Long
hEvent As Long
End Type
Private Const STARTF_USESHOWWINDOW = &H1
Private Const STARTF_USESTDHANDLES = &H100
Private Const SW_HIDE = 0
Private Const EM_SETSEL = &HB1
Private Const EM_REPLACESEL = &HC2
Private Sub Command1_Click()
Command1.Enabled = False
Redirect Text1.Text, Text2
Command1.Enabled = True
End Sub
Private Sub Form_Load()
Text1.Text = "ping"
End Sub
Private Sub Form_QueryUnload(Cancel As Integer, UnloadMode As Integer)
If Command1.Enabled = False Then Cancel = True
End Sub
Sub Redirect(cmdLine As String, objTarget As Object)
Dim i%, t$
Dim pa As SECURITY_ATTRIBUTES
Dim pra As SECURITY_ATTRIBUTES
Dim tra As SECURITY_ATTRIBUTES
Dim pi As PROCESS_INFORMATION
Dim sui As STARTUPINFO
Dim hRead As Long
Dim hWrite As Long
Dim bRead As Long
Dim lpBuffer(1024) As Byte
pa.nLength = Len(pa)
pa.lpSecurityDescriptor = 0
pa.bInheritHandle = True
pra.nLength = Len(pra)
tra.nLength = Len(tra)
If CreatePipe(hRead, hWrite, pa, 0) <> 0 Then
sui.cb = Len(sui)
GetStartupInfo sui
sui.hStdOutput = hWrite
sui.hStdError = hWrite
sui.dwFlags = STARTF_USESHOWWINDOW Or STARTF_USESTDHANDLES
sui.wShowWindow = SW_HIDE
If CreateProcess(vbNullString, cmdLine, pra, tra, True, 0, Null, vbNullString, sui, pi) <> 0 Then
SetWindowText objTarget.hwnd, ""
Do
Erase lpBuffer()
If ReadFile(hRead, lpBuffer(0), 1023, bRead, ByVal 0& Then
SendMessage objTarget.hwnd, EM_SETSEL, -1, 0
SendMessage objTarget.hwnd, EM_REPLACESEL, False, lpBuffer(0)
DoEvents
Else
CloseHandle pi.hThread
CloseHandle pi.hProcess
Exit Do
End If
CloseHandle hWrite
Loop
CloseHandle hRead
End If
End If
End Sub
Номер ответа: 21
Автор ответа:
KreAtoR
Вопросов: 120
Ответов: 438
Профиль | | #21
Добавлено: 26.08.07 13:47
2Arcady
Ба, это именно то, что мне надо!!!!! Бааа в самую точку. Расибо тебе огромное. И кода у тя гораздо меньше. Без класса и модуля. Класс.
Но как я понимаю
Dim pra As SECURITY_ATTRIBUTES
Dim tra As SECURITY_ATTRIBUTES
Dim pi As PROCESS_INFORMATION
Dim sui As STARTUPINFO
это не консоль. Есть ли все таки какая нить возможность в этом коде выводить text1 и text2 на консоль?
Arcady пасибо еще раз и если могешь расскажи что здесь в действительности происходит, чтоб я это выучил и потом знал где можно применить.
Номер ответа: 22
Автор ответа:
KreAtoR
Вопросов: 120
Ответов: 438
Профиль | | #22
Добавлено: 26.08.07 14:01
2 RA (Millenium)
regEdit в принципе можно использовать без проблем. И я собственно могу это сделать. Но сегодня это надо сделать через консоль. В этом беда.
2Arcady
консоль мне в принципе больше не нужна твоего примера хватает вполне. Вопрос только как открыть файл, к примеру блокнот. Или чтоб на text2 было выведено "C:\Documente und Einstellungen\Administrator>"
в text1 можно набрать "cd C:\WINDOWS\" а после чего на text2 выводится новое местоположение "C:\WINDOWS> . После чего набрать в text1 "NOTEPAD.EXE" и после нажатия на Command1 у нас просто открывался блокнот.
Номер ответа: 23
Автор ответа:
Mr.Smile
ICQ: 427682013
Вопросов: 14
Ответов: 464
Профиль | | #23
Добавлено: 26.08.07 14:36
2KreAtoR
Данный пример рассчитан на то, что приложение, которое ты запускаешь будет консольным.
Как я понял, ты пишешь аналог Командной строки. И тебе надо чтобы твоя программа полностью транслировала открытую (но скрытую) командную строку, включая такие команды, как cd, cls, exit и т.п.
Это не так-то просто, как кажется. Пока больше помочь ничем не могу.
Можешь задать свой вопрос здесь:
http://www.kbyte.ru/Expert/?lang=ru
P.S.: Это не реклама.