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

Вниз

Вопрос по CONSTRUCTOR у   Найти похожие ветки 

 
Stelius   (2002-06-28 00:35) [0]

Мастера, подскажите, pls. Вот такая проблема: есть прога без единой формы, хотелось бы создать в ней Timer с соответствующим событием OnTime, вопрос - как?


 
Oleg_Gashev   (2002-06-28 00:43) [1]

SetTimer QuickInfo Overview Group

The SetTimer function creates a timer with the specified time-out value.

UINT SetTimer(

HWND hwnd, // handle of window for timer messages
UINT idTimer, // timer identifier
UINT uTimeout, // time-out value
TIMERPROC tmprc // address of timer procedure
);


Parameters

hwnd

Identifies the window to be associated with the timer. If this parameter is NULL, no window is associated with the timer and the idTimer parameter is ignored.

idTimer

Specifies a nonzero timer identifier. If the hwnd parameter is NULL, this parameter is ignored.

uTimeout

Specifies the time-out value, in milliseconds.

tmprc

Points to the function to be notified when the time-out value elapses. For more information about the function, see the TimerProc callback function.
If tmprc is NULL, the system posts a WM_TIMER message to the application queue. The hwnd member of the message"s MSG structure contains the value of the hwnd parameter.



Return Value

If the function succeeds, the return value is an integer identifying the new timer. An application can pass this value, or the string identifier, if it exists, to the KillTimer function to destroy the timer. If the function fails to create a timer, the return value is zero.

Remarks

An application can process WM_TIMER messages by including a WM_TIMER case statement in the window procedure or by specifying a TimerProc callback function when creating the timer.
The wParam parameter of the WM_TIMER message contains the value of the idTimer parameter.

See Also

KillTimer, MSG, TimerProc, WM_TIMER

(C) Borland


 
Stelius   (2002-06-28 01:34) [2]

Согласен, что вопрос глупый, но я чего-то не доганю. Где здесь имя Timer"а? Тип idTimer: Cardinal, может выше строки SetTimer надо связать idTimer и имя Timer"а, как это делается?
И еще правильно ли я понял, что в TimeProc надо писать имя процедуры, типа Timer1OnTimer? И нужен ли у этой процедуры параметр Sender, если да, то как это записывается?
Очень поможете если подскажете.


 
ZmeyKA   (2002-06-28 20:37) [3]

хех... а когдато и был таким бестолковым и не умел читать по английски....

вобщем на первые два поля забиваем... т.е. ставим туда 0.
в 3 ставим время в четвертое ставим @ProcName , где ProcName это та самая процедура которая будет вызвана при срабатывании таймера..
Вот её описание..на С.

void CALLBACK TimerProc(
HWND hwnd,
UINT uMsg,
UINT idEvent,
DWORD dwTime
);
Parameters
hwnd
[in] Handle to the window associated with the timer.
uMsg
[in] Specifies the WM_TIMER message.
idEvent
[in] Identifier of the timer.
dwTime
[in] Specifies the number of milliseconds that have elapsed since the system was started. This is the value returned by the GetTickCount function.
Return Values
None.

вобщем по русски это звучит примерно так:

var TimerID:DWord;

procedure OnTimerProc (Wnd:Cardinal;Msg:cardinal; idEvent:cardinal;dwTime:cardinal);far;stdcall;
begin
{wnd здесь будет равно ноль}
{Msg здесь будет равно ноль}
{ idEvent здесь будет равно TimerId}
{dwTime здесь будет равно времени работы системы}
form1.caption:= "Таймер"+inttostr(idEvent)+" сработал";

end;


//////////////
{запускаем таймер}
TimerID=SetTimer(0,0,3567,@OnTimerProc);

///////////


//////////////
{Убиваем таймер}

KillTimer(TimerID);
/////////////////////


И напоследок... практически все функции являются частью WinApi ...пользуйся MSDN или встроеным в Делфи хелпом Windows SDK


 
Stelius   (2002-06-28 22:04) [4]

2ZmeyKA
Спасибо, за подробное разъяснение, помогло :).

Но (это вездесущее "но"), есть маленькая непонятка, а именно:
У моей проги нет ни единого окна, а OnTimer работает, только когда висит какое-нибудь окошко, например, от ShowMessage (или я опять чего-то не догоняю). Как бы получить событие OnTimer без окошек?


 
kaif   (2002-06-29 04:23) [5]

А нельзя просто создать экземляр банального TTimer?
А еще лучше потомка, чтобы был метод объекта, чтобы к событию OnTimer присобачить:

unit MyUnit;

interface

uses extctrls;

type

TMyTimer = class(TTimer)
procedure TimerEvent(Sender: TObject);
end;

implementation

var
Timer: TMyTimer;

procedure TMyTimer.TimerEvent(Sender: TObject);
begin
{мой код}
end;

initialization
Timer := TMyTimer.Create(nil);
Timer.OnTimer := Timer.TimerEvent;
Timer.Interval := 1000;
Timer.Enabled := True;
finalization
Timer.Free;
end;

--------------------------
Конечно, это не круто, но может заработает?


 
Роман Василенко   (2002-06-29 13:09) [6]

Stelius © (28.06.02 00:35)
Склоняюсь к тому, что вариант Олега Гашева самый лучший.

А чтобы без окна работал, поставь HWND=0. Это десктоп, если не ошибаюсь.


 
Stelius   (2002-06-29 16:19) [7]

2Роман Василенко. Дык в том-то и проблема, что HWHD=0, а OnTime не наступает, прога просто пробегает код от begin"а к end"у. А вот если поставить ShowMessage и пока появившееся окошко не закрывать OnTime прекрасно работает, а когда закрываешь - всё прекращается :(


 
Юрий Зотов   (2002-06-29 17:20) [8]

> прога просто пробегает код от begin"а к end"у

Если в программе нет Application (или не вызывается Application.Run), то так и должно быть - ведь в ней нет цикла выборки сообщений и вызова DispatchMessage. Делайте его ручками, иначе никакой таймер работать не будет - ни дельфишный TTimer, ни установленный Вами напрямую через SetTimer.

Есть и другой способ реализации таймера, не требующий ни окон, ни цикла выборки сообщений. Создаете второй поток с высоким приоритетом, который в течение заданного интервала времени просто спит, а затем выдает уведомление первому. Все это в цикле, разумеется.



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

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

Наверх





Память: 0.47 MB
Время: 0.012 c
4-47892
CoD
2002-05-13 19:37
2002.07.15
Вход в Windows XP


1-47428
Explorer
2002-07-03 09:16
2002.07.15
Как зарегистрировать EhLib?


1-47436
ded_di
2002-07-02 14:36
2002.07.15
Как подредактировать TOpenDialog?


3-47206
koty
2002-06-19 02:41
2002.07.15
Управление доступом.


14-47677
cyborg
2002-06-17 11:37
2002.07.15
ПАМЯТЬ НЕ ОСВОБОЖДАЕТСЯ!!!





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