Главная страница
    Top.Mail.Ru    Яндекс.Метрика
Форум: "WinAPI";
Текущий архив: 2002.09.05;
Скачать: [xml.tar.bz2];

Вниз

EditBox   Найти похожие ветки 

 
asmer   (2002-07-02 14:34) [0]

типа, такая вот тема... как в едит-бокс текст дописывать (а не замещать функцией SetWindowText)?.. типа, в СДК есть чё-та про получение\установку буфера, в котором лежат буковки... тока у меня чёй-то не получается... вроде всё так делаю, как написано (у диалога стиль LOCALEDIT стоит, сам едит-бокс многострочный, предыдущий буфер освобождаю функцией LocalFree, выделяю новый...), тока када я пытаюсь-таки в него чё-нить записать, винда мессагу выкидывает, что, мол, низзя туда писать...
благодарю за полный и развёрнутый ответ :)


 
Poirot   (2002-07-02 15:55) [1]


> asmer

А если просто GetWindowText и записать назад SetWindowText...
Не пробовал.... ASMER- хе... чё внатуре такой крутой....


 
asmer   (2002-07-02 17:52) [2]

типа, да, крутой... хех... ентот способ не есть кульно, я ж грю о конкретной весчи - работа з буфером, де буковки лежат... мне б о нём бы узнать... :) а туда-сюда гонять текст с помощью сет\гет не прикольно, када дописывать нужно слово, например, из трёх букв к тексту из трёх тысяч... :) сё равно спасибо за внимание, типа... поирот :)


 
Игорь Шевченко   (2002-07-02 17:54) [3]

asmer (02.07.02 17:52)

Оно надо - до внутреннего буфера добираться?
Сильно непростое дело...


 
asmer   (2002-07-02 17:59) [4]

да... ответ, канеш, сильный... :) непростое дело, типа... хех... было б простое, не спрашивал бы :) а если без буфера, тада предложи способ резонный...
заранее благодарен...


 
msts   (2002-07-02 18:59) [5]

Вот зануда а, весь день одно и тоже :))
Примерно так, накопал в хелпе:

EM_SETSEL - выбрать место/текст куда вставлять текст
EM_REPLACESEL - заменить текст

edLog.Handle - HWND едита

SendMessage(edLog.Handle,EM_SETSEL,-1,0);
SendMessage(edLog.Handle,EM_REPLACESEL,0,integer(PChar("TEST")));


An application sends an EM_SETSEL message to select a range of characters in an edit control.

EM_SETSEL
wParam = (WPARAM) (INT) nStart; // starting position
lParam = (LPARAM) (INT) nEnd; // ending position

Remarks

In a rich edit control, if the selection is not entirely contained in the first 64K, use the message EM_EXSETSEL.
If the nStart parameter is 0 and the nEnd parameter is -1, all the text in the edit control is selected. If nStart is -1, any current selection is removed. The caret is placed at the end of the selection indicated by the greater of the two values nEnd and nStart.
In previous versions of Windows, the wParam parameter is a flag that is set to FALSE to scroll the caret into view or set to TRUE to omit the scrolling. A Win32-based application should use the EM_SCROLLCARET message to scroll the caret into view.

In earlier versions of Windows, the starting and ending positions of the selection are indicated by the low- and high-order words, respectively, of the lParam parameter.

An application sends an EM_REPLACESEL message to replace the current selection in an edit control with the specified text.

EM_REPLACESEL
fCanUndo = (BOOL) wParam ; // flag that specifies whether replacement can be undone
lpszReplace = (LPCTSTR) lParam ; // pointer to replacement text string


Parameters

fCanUndo

Value of wParam. Specifies whether the replacement operation can be undone. If this is TRUE, the operation can be undone. If this is FALSE , the operation cannot be undone.

lpszReplace

Value of lParam. Points to a null-terminated string containing the replacement text.



Return Values

This message does not return a value.

Remarks

Use the EM_REPLACESEL message to replace only a portion of the text in an edit control. To replace all of the text, use the WM_SETTEXT message.
If there is no current selection, the replacement text is inserted at the current location of the caret.


 
asmer   (2002-07-02 19:12) [6]

млин... не катит... енто я читал... да и вааще, я весь хелп по поводу едит-бокса почитал... я ж и способ конкретный нашёл, тока вот сообразить не могу, почему он у меня не работает... а выделять-вставлять, енто аналогично сет\гет... не, не катит, там сё равно память нужно выделять при каждом поступлении порции символов... надо поспортивнее чё-нить :)


 
msts   (2002-07-02 19:54) [7]

непонял ? какая память? чего выделять?
пример из VCL Delphi 6
procedure TCustomComboBoxEx.SetSelText(const Value: String);
begin
if FStyle in [csExSimple, csExDropDown] then
begin
HandleNeeded;
SendMessage(FEditHandle, EM_REPLACESEL, 0, Longint(PChar(Value)));
end;
end;
можно сказать Word так делает


 
asmer   (2002-07-02 21:53) [8]

тока пример твой относится к комбо-боксу, во-первых... во-втрых, приведённая функция просто выделяет искомый участок текста... а в третьих, енто почти тож самое (преувеличенно, канеш), если б я посылал сообщения приложению, мол, кликнуть на едит-боксе, чтоб передать ему фокус, потом нажать [end], чтоб переместиться в конец текста, а потом ещё посылать нажатия клавиш, соответствующих символам, которые я хочу дописать в конце... типа, в таком виде я хотел сказать, что енти сообщения предназначены только для реализации интерфейса пользователя (например, сделать на панельке кнопки с алфавитом :)), а мне надо потоком писать в едит-бокс, и мне должно быть параллельно, какие символы там решил выделить пользователь... ворд сто пудово не использует енти сообщения (для таких целей), даю руку билла на отсечение... :)
с уважением, асмер, млин...


 
Diamond Cat   (2002-07-03 00:51) [9]

ну попробуй через sendmessage(...,Wm_paste,0,0) по идее должен вставлять текст из буфера обмена в то место где стоит курсор, а отпозиционировать курсор и заполнить буфер обмена думаю не проблема


 
asmer   (2002-07-03 14:10) [10]

ну ё-моё... я ж грю, мне должно быть параллельно, де пользователь выделил текст, где он курсор поставил и тэдэ... но и мешать пользователю ставить курсор куда попало тож не хочется, да к тому же текст будет мигать при интенсивной записи в него - окно будет постоянно перерисовываться... мне б про буфер-таки узнать, а?.. :)


 
msts   (2002-07-03 16:36) [11]

Может всеже необходимо делать добавление текста SETSEL - ведь едит должен знать что размер буфера изменился
я вот делал так - запоминал позицию каретки, хидил выделение,
перемещал каретку в нужное место, вставлял текст, возвращал все назад - и ничего не мерцало - прям в тексте было поле с текущим временем до msecунд,
это отступление - вот что нашел (типа нужно создать едит с DS_LOCALEDIT тогда память под буфер будет в сегменте приложения и им можно управлять - попробуй):
_____________________________
When Windows creates an edit control, it automatically creates a text buffer, sets its initial size, and increases the size as necessary. The size can be up to a predefined limit of approximately 32 kilobytes for single-line edit controls. Because this limit can change, it is called a soft limit. An application can set a hard limit to the buffer size by sending an EM_SETLIMITTEXT message to the edit control. If the buffer exceeds either limit, Windows sends the application an EN_ERRSPACE message. An application can retrieve the current text limit by sending an EM_GETLIMITTEXT message.

Windows typically creates an edit control buffer in a dialog box, using memory outside the application"s data segment. An application can suppress this default allocation behavior and create the buffer from its local heap by using the DS_LOCALEDIT style when creating the edit control. An application that uses the DS_LOCALEDIT style is responsible for all buffer allocations. To make the initial allocation, an application can call the LocalAlloc function and pass the returned buffer handle to the edit control by sending it an EM_SETHANDLE message. To make subsequent allocations (in response to an EN_ERRSPACE message, for example), an application should save the current buffer content (if necessary) and obtain a new buffer as follows:

1. Retrieve the handle of the memory currently allocated for the text in a multiline edit control by sending the control an EM_GETHANDLE message.
2. Free the buffer by calling the LocalFree function.
3. Obtain a new buffer (and buffer handle) by calling LocalAlloc.
4. Give the buffer handle to Windows by sending the control an EM_SETHANDLE message.



The EM_SETHANDLE and EM_GETHANDLE messages apply only to multiline edit controls.
An application that uses the default allocation behavior (that is, does not use the DS_LOCALEDIT style) must not send EM_SETHANDLE and EM_GETHANDLE messages to the edit control.
Sending an EM_SETHANDLE message has several side effects: it clears the undo flag (making the EM_CANUNDO message return zero), it clears the modify flag (making the EM_GETMODIFY message return zero), and it redraws the edit control window.
_____________________________
Before an application sets a new memory handle, it should send an EM_GETHANDLE message to retrieve the handle of the current memory buffer and should free that memory.
An edit control automatically reallocates the given buffer whenever it needs additional space for text, or it removes enough text so that additional space is no longer needed.
Sending an EM_SETHANDLE message clears the undo buffer (EM_CANUNDO returns zero) and the internal modification flag (EM_GETMODIFY returns zero). The edit control window is redrawn.

An application can send this message to a multiline edit control in a dialog box only if it has created the dialog box with the DS_LOCALEDIT style flag set.


 
asmer (faq)   (2002-07-03 17:41) [12]

хех... наконец-то ты нашёл то, о чём я спрашивал!.. типа, именно енто я и прочитал перед тем, как написал сюда свой вопрос :) дык вот, я делаю так, как написано в справке, а винда возмущается, что, типа, прога к памяти обращается, к которой обращаться её совсем не положено!.. если я добьюсь результата раньше - напишу сюда, так уж и быть :)) спасибо за проявленный интерес, мож, у кого-нить-таки чё-нить получится - напишите рабочую функцию, пожалуйста...



Страницы: 1 вся ветка

Форум: "WinAPI";
Текущий архив: 2002.09.05;
Скачать: [xml.tar.bz2];

Наверх





Память: 0.49 MB
Время: 0.008 c
14-14217
Fiend
2002-08-09 15:08
2002.09.05
Сертифицирование


7-14304
Ильнур
2002-06-22 12:08
2002.09.05
Работа со сканером


4-14324
lds78
2002-07-03 10:16
2002.09.05
Аналоги IntToStr и StrToInt в WinAPI


1-14098
ErmSergey
2002-08-23 15:33
2002.09.05
Помогите с ошибкой


1-13993
Mr.Kirya
2002-08-25 21:03
2002.09.05
Нужен компонент...





Afrikaans Albanian Arabic Armenian Azerbaijani Basque Belarusian Bulgarian Catalan Chinese (Simplified) Chinese (Traditional) Croatian Czech Danish Dutch English Estonian Filipino Finnish French
Galician Georgian German Greek Haitian Creole Hebrew Hindi Hungarian Icelandic Indonesian Irish Italian Japanese Korean Latvian Lithuanian Macedonian Malay Maltese Norwegian
Persian Polish Portuguese Romanian Russian Serbian Slovak Slovenian Spanish Swahili Swedish Thai Turkish Ukrainian Urdu Vietnamese Welsh Yiddish Bengali Bosnian
Cebuano Esperanto Gujarati Hausa Hmong Igbo Javanese Kannada Khmer Lao Latin Maori Marathi Mongolian Nepali Punjabi Somali Tamil Telugu Yoruba
Zulu
Английский Французский Немецкий Итальянский Португальский Русский Испанский