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

Вниз

Высота строк в RichEdit е   Найти похожие ветки 

 
TStas   (2012-05-16 02:03) [0]

Как получить высоту строки с известным номером в RichEdit"е? Неужели всю строку посимольно проверять и вычислять высоту каждого, а потом брать максимальную? Понятно, что всё порлучится, но должно же у него это как-то проще делаться?


 
KilkennyCat ©   (2012-05-16 02:58) [1]

drawtext c флагом DT_CALCRECT (и ни в коем разе не задавать ей TRect типа (0,0,0,0) - вернет неверный результат)


 
KilkennyCat ©   (2012-05-16 03:00) [2]

http://msdn.microsoft.com/en-us/library/dd162498%28v=vs.85%29.aspx


 
MBo ©   (2012-05-16 05:31) [3]

Думаю, задача должна решаться с помощью EM_*** - сообщений


 
KilkennyCat ©   (2012-05-16 09:54) [4]


> MBo ©   (16.05.12 05:31) [3]

да, ты прав. не подумал, что в ричьедите каждая буква может быть совершенно иной.
тогда EM_GETCHARFORMAT и
> Неужели всю строку посимольно проверять

да


 
Leonid Troyanovsky ©   (2012-05-16 10:12) [5]


> TStas   (16.05.12 02:03)  

> Как получить высоту строки с известным номером в RichEdit"е?

http://www.rsdn.ru/forum/delphi/692316.hot.aspx

--
Regards, LVT.


 
MBo ©   (2012-05-16 14:04) [6]

Леонид, ты держишь упорядоченную коллекцию ссылок или хорошо помнишь, где чего писал?


 
TStas   (2012-05-16 15:04) [7]

>Leonid Troyanovsky Спасибо. Рект под курсором, кстати, тоже вещь крайне нужная.
>KilkennyCat А что ф-ции передавть? Рект передавать ControlCanvas.ClipRect?
Handle какой? ControlCanvas.Handle? Ну и в начале ControlCanvas создать и присвоить свой ричЭдит?
За ответы спасибо, но вот как выловить высоту строчки с известным номером?
Сообщения ЕМ_ХХХ я тоже думал послать ему. Но не понятно, какое именно, вроде среди этих сообщений я подходящего не нашёл, возможно, просто плохо посмотрел, их ведь весьма много. А что в параметрах сообщения передавать и, главное, результат-то где смотреть?


 
Leonid Troyanovsky ©   (2012-05-16 16:34) [8]


> MBo ©   (16.05.12 14:04) [6]

> Леонид, ты держишь упорядоченную коллекцию ссылок или хорошо
> помнишь, где чего писал?

Помню не очень хорошо. Иногда помнится, что по этому поводу
был треп. За подробностями лезу в гугль, если что-то зацепило.

--
Regards, LVT.


 
Leonid Troyanovsky ©   (2012-05-16 16:43) [9]


> TStas   (16.05.12 15:04) [7]

> За ответы спасибо, но вот как выловить высоту строчки с
> известным номером?

Надо немного напрячь мыслительную мышцу.
Для строки с курсором определяется lineidx, тебе же оное уже известно.

--
Regards, LVT.


 
TStas   (2012-05-18 14:24) [10]

Уже напряг и всё отловил :).
А вот ещё вопрос, чтобы ветку не создавать. Пробовал паодменять табулятор двумя пробелами. Пробовал по-всякому, в первую очередь путём перехвата WM_KEYDOWn WM_KEYUP. Всё ловится, а вот подмены не просисходит. Подменять пробовал путём посылки себе же сообщения в другим кодом клавиши. Даже не убирается табулятор. Однако как-то делал похожие вещи, только со свтавкой при определённом сочитании клавиш спецсимволов. Всё получалось, только делал через компонент ApplicationEvent. А почему так? В поле Result помещал ненулевые значения и inherited не вызывал.
Код выложить не могу, ибо стёр, потому как не работает.


 
Leonid Troyanovsky ©   (2012-05-21 11:25) [11]


> TStas   (18.05.12 14:24) [10]

> А вот ещё вопрос, чтобы ветку не создавать. Пробовал паодменять
> табулятор двумя пробелами.

Дельфи под рукой нет, но попробуй как-то так:

procedure TFormX.CMDialogKey(var msg: TCMDialogKey); // message cm_DialogKey;
begin
if (msg.CharCode = vk_tab) and (...) then
  begin
    if ActiveControl is TRichedEdit then
      begin
        msg.CharCode := vk_space;
        PostMessage(ActiveControl.Handle, WM_CHAR, vk_space, 0);
      end;
  end;
inherited;
end;

--
Regards, LVT.


 
Leonid Troyanovsky ©   (2012-05-21 11:29) [12]


> TStas   (18.05.12 14:24) [10]

>  Всё получалось, только делал через компонент ApplicationEvent.
>  А почему так?

By Peter Below (TeamB) :
<quote>
The control with focus will not receive all keys. The Windows/VCL key
handling mechanism works like this:

1. you press a key.
2. a WM_KEYDOWN or WM_SYSKEYDOWN message is put into the applications
   message queue.
3. the message loop code retrieves the message and, after some checks
   for special treatments (e.g. for MDI) hands it to a VCL function.
4. The function converts the message to a CN_KEYDOWN message and sends it
   to the control with focus.
5. The handler for this message in TWinControl first checks if the key
   is a keyboard shortcut for a menu item on the controls popup menu (if
   any), if not it checks all the popup menus of the controls parent
   controls and finally the forms main menu (if any). During this process
   the forms IsShortcut method is called and fires the OnShortcut event.
6. If it is not a menu shortcut the key event is next send as a
CM_CHILDKEY
   message to the control. The handler for this message in TWinControl
does
   nothing more than sending it to the controls parent. It will thus work
   its way up the parent chain until it finally reaches the form. This
   constitutes the first chance to trap the key event at the form level.
7. If the CM_CHILDKEY message is not handled by any receiver (none sets
   msg.result to 1) the code in TWincontrol.CNKeyDown then asks the
control
   whether it wants to handle the key event. However, it does this only
if
   the key is one of the following: VK_TAB, VK_LEFT, VK_RIGHT, VK_UP,
   VK_DOWN, VK_RETURN, VK_EXECUTE, VK_ESCAPE, VK_CANCEL, all other keys
   will be delivered to the control without further checks.
   CNKeyDown sends two messages to the control for these keys:
7a.CM_WANTSPECIALKEY
7b.WM_GETDLGCODE (which is the message Windows standard controls expect
   and handle).
8. If the control does not express an interest in the key (Tedit controls
   do not want VK_TAB, for instance) a CM_DIALOGKEY message is send to
the
   form for these special keys. The default handler for this message in
   TCustomForm handles the navigation between controls in response to the
   key events and marks the message as handled. This message is the
second
   opportunity to trap these keys on the form level. The default handler
   broadcasts the message to all TWinControls on the form, this is the
   way default and cancel buttons get aware of return and Escape key
   events even if they do not have the focus.
9. If the key message is still not marked as handled (msg.result is still
0)
   the code path returns to the message loop and the message is finally
   handed to the API functions TranslateMessage (which generates a
WM_CHAR
   message if the key produces a character) and DispatchMessage (which
sends
   the key message to the controls window proc).
10. The controls handler for WM_KEYDOWN receives the message. The handler
in
   TWinControl calls the DOKeyDown method, passing the message
parameters.
11. DoKeyDown checks if the parent forms KeyPreview property is true, if
so
   it directly calls the DoKeyDown method of the form, which fires the
forms
   OnKeyDown event. If the Key is set to 0 there, no further processing
is
   performed.
12. DoKeyDown calls KeyDown (which is virtual and can thus be overriden),
   TWinControl.KeyDown fires the controls OnKeyDown event. Again, if Key
is
   set to 0 there, no further processing is done on it.
13. Code flow returns to TWinControl.WMKeyDown, which calls the inherited
   handler. The key event finally gets to the default window function
   this way and may cause a visible action in the control.

As you can see the path of a key message is quite complicated. If you
press the tab key in an edit control the message will get up to step 8 and
then be processed on the form level as CM_DIALOGKEY, it is marked as
handled there, so all the steps further down are not executed and the
control never sees the WM_KEYDOWN message for it, so its OnKeyDown handler
never fires for a Tab.

The process offers the following points of intervention on the form level:

a) Application.OnMessage
This event is fired directly after the message has been retrieved from
the message queue in step 3, before anything further is done for it.
The event sees all messages that go through the message loop, not only
key messages.
b) The forms OnShortcut event.
c) CM_CHILDKEY
If you add a handler for this message to the form it will see all key
events with the exeption of menu shortcuts. Such a handler would see
all tab key events, but also many others.
d) CM_DIALOGKEY
If you add a handler for this message it will see all the keys mentioned
in step 7, unless the control wants to handle them itself. This handler
would see VK_TAB if the active control is not a TMemo with WantTabs =
True or a TRichedit or grid control, for instance. I think for your
purpose handling CM_DIALOGKEY would be the correct choice. Do not forget
to call the inherited handler or form navigation will cease to work.

</quote>
--
Regards, LVT.


 
TStas   (2012-05-21 23:09) [13]

Леонид, спасибо за ответ. Я уже всё решил. Решил так:
   procedure CNKeyDown(var Message: TMessage); message CN_KEYDOWN;
   procedure CNKeyUP(var Message: TMessage); message CN_KEYUP;
Ну и в них, если клавиши перехвачены, то просто Result ненулевым делаю и Inherited не вызываю. Наверно, что-то из этих двух действий лишнее, но всё работает и трогать не хочется.
  Через procedure TFormX.CMDialogKey(var msg: TCMDialogKey); // message cm_DialogKey, как Вы написали, делать было никак нельзя, поскольку пишу, вернее, уже написал и дописываю редакторы свойств и т. п, компонент. А компонент обязан быть независимым, иначе это не компонент.
  Сейчас буду читать, что ВЫ выложили. Просто было непонятно, почему WM_KEY... вообще не доходят, а приходят CN_KEY... Мне кажется, что кто-то из славных предков перехватывает WM_KEY... и преобразует их в CN_KEY... Компонент - наследник RichEdita. Мне кажется, это CustomEdit делает.


 
Leonid Troyanovsky ©   (2012-05-22 09:46) [14]


> TStas   (21.05.12 23:09) [13]

>  // message cm_DialogKey, как Вы написали, делать было никак
> нельзя, поскольку пишу, вернее, уже написал и дописываю
> редакторы свойств и т. п, компонент. А компонент обязан
> быть независимым, иначе это не компонент.

Для обработки табов ему, кроме того, нужно WantTabs.
Ну, или хендлеры CM_WANTSPECIALKE/WM_GETDLGCODE.

--
Regards, LVT.



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

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

Наверх





Память: 0.5 MB
Время: 0.07 c
2-1335425564
jacksotnik
2012-04-26 11:32
2013.03.22
TreeView &amp; Checkbox


15-1353414294
Сергей М.
2012-11-20 16:24
2013.03.22
Непонятка на стыке ajax и PHP


15-1346949988
Опять я
2012-09-06 20:46
2013.03.22
Как вывести ВЕКТОРНУЮ линию в Delphi?


15-1340712165
картман
2012-06-26 16:02
2013.03.22
кластеризация


8-1226309625
Andrey_ka
2008-11-10 12:33
2013.03.22
как работает PixelFormat





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
Английский Французский Немецкий Итальянский Португальский Русский Испанский