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

Вниз

Alt+f4   Найти похожие ветки 

 
Ted   (2002-01-03 10:38) [0]

Помогите кто нибудь!
Не могу разобраться почему в запущеной форме отслеживающей Alt+f4
при нажатии и удержании Alt+f4 форма закрывается?

procedure TForm1.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if (ssAlt in Shift) and (key = Vk_F4) then
MessageDlg("Нажато Alt+f4)", mtInformation, [mbOK],0)
else

MessageDlg("не нажато Alt+f4", mtInformation, [mbOK],0);
Как отключить закрытие формы???


 
gek   (2002-01-03 11:12) [1]

KeyPreview установлено в true?


 
valery_f   (2002-01-03 11:41) [2]

2Ted. А ты не забыл сбросить key, например, в ноль? :))))))


 
Юрий Зотов   (2002-01-03 12:14) [3]

> Как отключить закрытие формы???

Увы, но Вы пошли по изначально неверному пути. Правильный - перехват WM_SYSCOMMAND. Детали см. в описании WM_SYSCOMMAND.


 
valery_f   (2002-01-03 14:22) [4]

>...Правильный - перехват WM_SYSCOMMAND...
Согласен, однако если в приведенном примере key сбросить в 0 - тоже работает (хотя я на это даже не надеялся :). Опробовано на D3.


 
gek   (2002-01-03 14:41) [5]

У меня на D5 и без WM_SYSCOMMAND и установки key в 0 нормально работает.


 
Виктор Щербаков   (2002-01-03 15:23) [6]

to Ted ©
если Вы хотите поймать сообщение закрытия формы, отправляемое только в случае нажатия alt+f4, то key нужно установить в 0 в Вашем коде, а если нужно поймать это сообщение в любом случае, то пишите свой обработчик для сообщения WM_SYSCOMMAND.


 
Юрий Зотов   (2002-01-03 15:48) [7]

> valery_f (03.01.02 14:22)
> gek (03.01.02 14:41)

Проверьте, будет ли работать Ваш код на MDIChild форме. Кроме того, форму можно закрыть и мышью, и через системное меню, и через кнопку на таскбаре.

А перехват WM_SYSCOMMAND сработает в любом случае. Потому что он ловит не клавиши и не клики, а саму команду на закрытие. Причем независимо от стиля окна.


 
valery_f   (2002-01-03 16:37) [8]

>...форму можно закрыть и мышью...
Дык речь шла только об Alt-F4 (хотя Ted, возможно, пытается перехватить все варианты...)

>...будет ли работать Ваш код на MDIChild форме...
если есть MDIChild"ы - конечно нет, но это частный случай :)))

А вообще, конечно, нестандартное использование дельфийских либ - это баловство. Раз уж лезть вглубь - лучше использовать API - это и проще, и надежнее.


 
Ted   (2002-01-04 10:34) [9]

Я перерыл Help но описания WM_SysCommand не нашел.
Что это за зверь, и с чем его едят??????
Если можно с примером...
Заранее благодарен...



 
gek   (2002-01-04 11:32) [10]

А где же ты енто дело ищешь-то?
Все в Windows SDK есть и описано подробно че делает


 
Vovchik   (2002-01-04 12:37) [11]

В самом-то деле, я тоже это хотел сказать. Вот копия из SDK (извиняюсь, форматирование убилось):

M_SYSCOMMAND

A window receives this message when the user chooses a command from the window menu (formerly known as the system or control menu) or when the user chooses the maximize button, minimize button, restore button, or close button.

WM_SYSCOMMAND

uCmdType = wParam; // type of system command requested
xPos = GET_X_LPARAM(lParam); // horizontal position, in screen coordinates
yPos = GET_Y_LPARAM(lParam); // vertical position, in screen coordinates

Parameters

uCmdType

Specifies the type of system command requested. This parameter can be one of the following values. Value Meaning

SC_CLOSE Closes the window.

SC_CONTEXTHELP Changes the cursor to a question mark with a pointer. If the user then clicks a control in the dialog box, the control receives a WM_HELP message.

SC_DEFAULT Selects the default item; the user double-clicked the window menu.

SC_HOTKEY Activates the window associated with the application-specified hot key. The lParam identifies the window to activate.

SC_HSCROLL Scrolls horizontally.

SC_KEYMENU Retrieves the window menu as a result of a keystroke. For more information, see the Remarks section.

SC_MAXIMIZE Maximizes the window.

SC_MINIMIZE Minimizes the window.

SC_MONITORPOWER Sets the state of the display. This command supports devices that have power-saving features, such as a battery-powered personal computer.

lParam can have the following values:

1 means the display is going to low power.
2 means the display is being shut off.

SC_MOUSEMENU Retrieves the window menu as a result of a mouse click.

SC_MOVE Moves the window.
SC_NEXTWINDOW Moves to the next window.
SC_PREVWINDOW Moves to the previous window.
SC_RESTORE Restores the window to its normal position and size.
SC_SCREENSAVE Executes the screen saver application specified in the [boot] section of the System.ini file.
SC_SIZE Sizes the window.
SC_TASKLIST Activates the Start menu.
SC_VSCROLL Scrolls vertically.

xPos

Specifies the horizontal position of the cursor, in screen coordinates, if a window menu command is chosen with the mouse. Otherwise, the xPos parameter is not used.

yPos

Specifies the vertical position of the cursor, in screen coordinates, if a window menu command is chosen with the mouse. This parameter is –1 if the command is chosen using a system accelerator, or zero if using a mnemonic.

Return Values

An application should return zero if it processes this message.

Remarks

The DefWindowProc function carries out the window menu request for the predefined actions specified in the previous table.

In WM_SYSCOMMAND messages, the four low-order bits of the uCmdType parameter are used internally by the system. To obtain the correct result when testing the value of uCmdType, an application must combine the value 0xFFF0 with the uCmdType value by using the bitwise AND operator.

The menu items in a window menu can be modified by using the GetSystemMenu, AppendMenu, InsertMenu, ModifyMenu, InsertMenuItem, and SetMenuItem functions. Applications that modify the window menu must process WM_SYSCOMMAND messages.

An application can carry out any system command at any time by passing a WM_SYSCOMMAND message to DefWindowProc. Any WM_SYSCOMMAND messages not handled by the application must be passed to DefWindowProc. Any command values added by an application must be processed by the application and cannot be passed to DefWindowProc.

Accelerator keys that are defined to choose items from the window menu are translated into WM_SYSCOMMAND messages; all other accelerator keystrokes are translated into WM_COMMAND messages.

If the wParam is SC_KEYMENU, the lParam contains the character code of the key that is used with the ALT key to display the popup menu. For example, pressing ALT+F to display the File popup will cause a WM_SYSCOMMAND with wParam equal to SC_KEYMENU and lParam equal to "f".

Requirements

Windows NT/2000: Requires Windows NT 3.1 or later.
Windows 95/98: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.

See Also

Keyboard Accelerators Overview, Keyboard Accelerator Messages, Power Management Overview, AppendMenu, DefWindowProc, GetSystemMenu, InsertMenu, ModifyMenu, WM_COMMAND


 
Ted   (2002-01-04 17:25) [12]

Блин наверное покажусь назойлевым идиотом, но кто нибудь пожайлуста объясните как пользоваться командой WM_SYSCOMMAND????
Заранее благодарен.....


 
valery_f   (2002-01-04 17:46) [13]

Сие блокирует обычные способы закрытия окна - Alt-F4 и кнопка с крестиком:

TForm1 = class(TForm)
...
private
procedure MySysCommand(var Message: TMessage); message WM_SYSCOMMAND;
...

procedure TForm1.MySysCommand(var Message: TMessage);
begin
if Message.WParam <> SC_CLOSE then inherited;
end;


 
Vovchik   (2002-01-04 19:39) [14]

Собственно, WM_SYSCOMMAND это не команда, а сообщение. Винда (и не только) иногда посылает их разным окнам. Но для отлова этого сообщения не обязательно делать отдельную процедуру, можно видимо отлавливать его в WndProc:

procedure TForm1.WndProc(var Message: TMessage);
begin
if Message.Msg=wm_syscommand then
begin
case Message.WParam of
SC_MAXIMIZE: ;
SC_MINIMIZE: ;
SC_RESTORE: ;
end;
end else inherited;
end;

Ну, или что-то типа этого.

2Ted
А ты вообще не знал про мессаджи?


 
Ted   (2002-01-05 11:05) [15]

Я только учусь......


 
Ted   (2002-01-05 11:13) [16]

Угу.....


 
Vovchik   (2002-01-05 12:46) [17]

Учись, иногда помогает. Ну, получилось перехватить?


 
Ted   (2002-01-05 13:12) [18]

Да, спасибо......



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

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

Наверх





Память: 0.49 MB
Время: 0.005 c
1-9194
[NIKEL]
2002-02-14 14:04
2002.03.04
Как быстро и без напряг реализовать такую штуку...


7-9307
CyberSnake
2001-11-30 00:52
2002.03.04
NTFS и свободное место


1-9235
lightix
2002-02-15 15:09
2002.03.04
Подскажите, как из программы передать данные в Excel?


6-9256
Vlad_NOJABR
2001-12-11 07:49
2002.03.04
Как распечатать содержимое HTML-страничики?


1-9134
pakko
2002-02-15 21:24
2002.03.04
Простой вопрос!





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