How to force Help and Printer Setup Dialogs to be displayed on the same monitor as the running application? - delphi

I know how to force forms to appear on the same monitor as the running application, but I do not see how to ask the Help or the Printer Setup dialogs to display on the same monitor. The Help displays where it displayed last time, but we want it to show up on the application monitor. The Printer Setup dialog always seems to appear on the primary monitor

Passing the parent form's Handle to TPrinterSetupDialog.Execute seems to do the trick.
if PrinterSetupDialog1.Execute(Self.Handle) then
//
Using Delphi 7 (where the TPrinterSetupDialog.Execute does not accept a parameter), you have two choices.
The easiest would be to create your own descendant of TPrinterSetupDialog. Execute is virtual in TCommonDialog, the ancestor of TPrinterSetupDialog, where it is overridden. You could override it in your own descendant, use the code in the TPrinterSetupDialog as a basis for your own Execute override, adding overload as well. Your overloaded Execute would accept a ParentHandle: HWND parameter, and set the PrintDlgRec.hWndOwner to that provided window handle.
I thought about trying to write this for you (or at least get it started), but there are additional things you'd have to copy from the Dialogs unit (functions that are defined in the implementation section that wrap some API calls, and the callback function that's used for the dialog's message loop), and I don't have D7 available where I'm at to even try to compile it.
The other alternative (as David Heffernan mentioned in his comment below) would be to call the Windows API PrintDlgEx directly yourself. This is discussed in MSDN, in the Print Dialog Box (Windows) topic. Once again, I don't have D7 available, so I can't really give you an example of using it from Delphi. (I checked, and don't have one tucked away anywhere.)
I'm not sure you can set the help window's position; I think that's done automatically by Windows based on the user's prior use. (I haven't been able to so so, anyway.)

Related

Delphi : in CreateForm, how to tell which component creation is slow

In my program, the creation of the main form is slow : I have identified that it hangs for around two seconds just before the form's OnCreate event is called. So I suspect this is happening while the components are created.
Since this form has several frames, I wonder if there is a way to "profile" component creation in order to see where I can improve. I suspect the lag comes from the opening of a database table that should not be open at that time (rather later, after some filtering is in place).
If there is a way get an event triggered before/after each component creation, I could do the profiling myself (with codesite for example).
Or maybe it is possible to do the component creation manually ?
Here is a quick and dirty way to work out where the delay is:
Take a copy of the Classes unit source code and place it in your project's source folder. This will ensure that this unit is compiled into your program rather than the one supplied with Delphi.
Modify the code in the constructor of TComponent. All streamed components pass through here during creation. Add code to log the class name, e.g. using CodeSite for instance.
Run your program, and then inspect the resulting log to identify the delay.
If you have many components then just knowing the class might not narrow it down. You might inject logging code into TComponent.SetName instead which will let you log the component's name. However, the basic idea is simple enough, and you should be able to apply it to your setting in order to find out the information you need.

Firemonkey - Message Handling

I'm currently trying to develop a project based upon Firemonkey. I'm using Firemonkey for it's UI features as the project consists of many smaller applications, each with a 3D aspect to it. I'm currently only developing/deploying to Windows with the FMX framework, but may go cross-platform at a later date.
I've gotten around most issues I've come across by building a VCL Windows application in the background to perform a very specific action, and then building an FMX frontend. However, this is only suitable when you only want to execute the application to perform that action it's designed to do, and thus can execute the application with parameters. In one of the applications, i've come upon the need to use messages (or something similar). For example, in my FMX application, if i click "button1", i want it to send a message to the background VCL application to perform "action1", rather than execute it with parameters.
A good example could be using the VCL TMediaPlayer in the background application, with the front-end FMX application being used to display the information and provide control of play, pause, etc. Such that it essentially becomes an FMX UI with VCL ability.
I've so far been unable to find anything on how messages (e.g. in VCL, they'd be done with "SendMessage" or "PostMessage" or something similar) are handled with Firemonkey, either through the local help file, or through extensive Googling. Everything i've turned up has been related to email (presumably because of the word "Message" in most of my search terms).
Can anyone point me in the right direction on how messages would be handled with Firemonkey/FMX?
Regards,
Scott Pritchard
My understanding is that Firemonkey is not based on traditional windows, so sending window messages to Firemonkey controls is not usually an option. Although some controls do use windows (most notibly, TCommonCustomForm), so you can use the FmxHandleToHWND() function in the FMX.Platform.Win unit to extract an HWND from a TFmxHandle when needed. I have no clue how to receive and custom process window messages in FMX controls, if that is even possible.
Firemonkey under Windows has access to the Win32 API, so there should be nothing stopping you from sending window messages to other windowed controls, such as your VCL UI. Include the Winapi.Windows unit in your uses clause to access Win32 API functions, just like you would in a VCL application.
UPDATE: because FireMonkey does not expose access to messages that are sent to a Form's window, you have to manually subclass the window in order to receive messages before FireMonkey sees them. You can override the Form's CreateHandle() method, call the inherited method first to create the window, then use FmxHandleToHWND() to get the HWND that you can subclass. Be sure to also override the DestroyHandle() method to remove the subclass before then calling inherited to release the HWND.
Currently, FireMonkey doesn't have a message handler that you can use to send and post messages.
There is a possibility of hooking things up using listeners like FireMonkey works internally, but none of it is documented.
So, instead, here's what I've done:
I created my own custom "message" class. I create instances of the class and add them to a thread-safe list from any thread I need to. On the main thread, I have a timer that checks the list and processes the "messages".

Making Sure A ShowMessage Stays On Top

I have a few applications and I call a ShowMessage('Complete!'); at the end of a long operation.
Most of the time, this works great, but every once in awhile, the Message Dialog will show up behind the main form.
Is there any way for me to ensure the ShowMessage will always be on top?
Thanks!
Call the Windows MessageBox() API instead and pass in the handle to the active form. Actually, my code uses Application.MainFormHandle all the time which I am therefore sure is a reasonable and simple approach.
This will have the benefit of being the system native dialog rather than the home-grown Delphi version. It supports clipboard operations also.
If you want to get very fancy then you can use the Vista task dialog, but that's much more complex and you clearly don't need it for such a simple dialog.

Is there a way to log every gui event in Delphi?

The Delphi debugger is great for debugging linear code, where one function calls other functions in a predictable, linear manner, and we can step through the program line by line.
I find the debugger less useful when dealing with event driven gui code, where a single line of code can cause new events to be triggered, which may in turn trigger other events.
In this situation, the 'step through the code' approach doesn't let me see everything that is going on.
The way I usually solve this is to 1) guess which events might be part of the problem, then 2) add breakpoints or logging to each of those events.
The problem is that this approach is haphazard and time consuming.
Is there a switch I can flick in the debugger to say 'log all gui events'? Or is there some code I can add to trap events, something like
procedure GuiEventCalled(ev:Event)
begin
log(ev);
ev.call();
end
The end result I'm looking for is something like this (for example):
FieldA.KeyDown
FieldA.KeyPress
FieldA.OnChange
FieldA.OnExit
FieldB.OnEnter
This would take all the guesswork out of Delphi gui debugging.
I am using Delphi 2010
[EDIT]
A few answers suggested ways to intercept or log Windows messages. Others then pointed out that not all Delphi Events are Windows messages at all. I think it is these type of "Non Windows Message" Events that I was asking about; Events that are created by Delphi code. [/EDIT]
[EDIT2]
After reading all the information here, I had an idea to use RTTI to dynamically intercept TNotifyEvents and log them to the Event Log in the Debugging window. This includes OnEnter, OnExit, OnChange, OnClick, OnMouseEnter, OnMouseLeave events. After a bit of hacking I got it to work pretty well, at least for my use (it doesn't log Key events, but that could be added).
I've posted the code here
To use
Download the EventInterceptor Unit and add it to your project
Add the EventInterceptor Unit to the Uses clause
Add this line somewhere in your code for each form you want to track.
AddEventInterceptors(MyForm);
Open the debugger window and any events that are called will be logged to the Event Log
[/EDIT2]
Use the "delphieventlogger" Unit I wrote download here. It's only one method call and is very easy to use. It logs all TNotifyEvents (e.g. OnChange, OnEnter, OnExit) to the Delphi Event Log in the debugger window.
No, there's no generalized way to do this, because Delphi doesn't have any sort of "event type" that can be hooked in some way. An event handler is just a method reference, and it gets called like this:
if assigned(FEventHandler) then
FEventHandler(self);
Just a normal method reference call. If you want to log all event handlers, you'll have to insert some call into each of them yourself.
I know it is a little bit expensive, but you can use Automated QA's (now SmartBear) TestRecorder as an extension to TestComplete (if you want this only on your system, TestComplete alone will do). This piece of software will track your GUI actions and store it in a script like language. There is even a unit that can be linked into your exe to make these recordings directly at the user's system. This is especially helpful when some users are not able to explain what they have done to produce an error.
Use WinSight to see the message flow in real time.
If you really want the program to produce a log, then override WinProc and/or intercept the messages in Application.
The TApplication.OnMessage event can be used to catch messages that are posted to the main message queue. That is primarily for OS-issued messages, not internal VCL/RTL messages, which are usually dispatched to WndProc() methods directly. Not all VCL events are message-driven to begin with. There is no single solution to what you are looking for. You would have to use a combination of TApplication.OnMessage, TApplication.HookMainWindow(), WndProc() overrides, SetWindowsHook(), and selective breakpoints/hooks in code.
Borland's WinSight tool is not distributed anymore, but there are plenty of third-party tools readily available that do the same thing as WinSight, such as Microsoft's Spy++, WinSpector, etc, for tracking the logging window messages in real-time.
As an alternative, to debug the triggered events use the debugger Step Into (F7) instead of Step Over (F8) commands.
The debugger will stop on any available code line reached during the call.
You can try one of the AOP frameworks for Delphi. MeAOP provides a default logger that you can use. It won't tell you what is going on inside an event handler but it will tell you when an event handler is called and when it returns.

Delphi, how to make independent windows

I have an application that uses tabs like the Chrome browser. Now I want to be able to open more forms and not be limited to only one form. These forms should act the same but if I close main form all forms are closed. How can I make all forms be equal, so no matter which form I close it only closes that form and not exit application before all forms are closed? Any ideas?
Image of my explorer
Kind Regards
Roy M Klever
It's not too hard to do this, though it starts getting complicated quickly depending on how complete you want it to be. Getting multiple modal dialogs to work independently is a ton of effort.
To start, you need to avoid Application.MainForm entirely. Always use Form := TMyForm.Create(Application) instead of Application.CreateForm(TMyForm, Form). The later sets MainForm and you never want that to happen.
To make things shut down properly you'll need to do something like this in your form's OnClose event handler:
if Screen.FormCount = 1 then
Application.Terminate;
CloseAction := caFree;
Application.Run relies on MainForm being assigned, so in your DPR replace that line with this loop:
repeat
try
Application.HandleMessage;
except
Application.HandleException(Application);
end;
until Application.Terminated;
There are a couple of ways to handle the taskbar entry.
Single taskbar entry: Set Application.MainFormOnTaskbar := False; and the hidden TApplication handle will be used. Clicking on the taskbar entry will bring all of the windows to the front. You'll need to override Application.OnMessage or add a TApplicationEvents component, and watch for WM_CLOSE with the Msg.Handle = Application.Handle`. In that case the user has right-clicked on the taskbar and selected Close, so you should close all the windows.
Multiple taskbar entries: Set Application.MainFormOntaskbar := True. Override your form's CreateParams method and set Params.WndParent := 0;. Each taskbar entry will control that form.
There are probably a few other gotchas, but that's the basics.
As I said, making ShowModal and TOpenDialog/TSaveDialog working independently, so it only affects its parent form and so multiple dialogs can be open at once, is a ton of work, and I can't really recommend it. If you're a masochist, here's the general steps:
Replace TCustomForm.ShowModal with a custom version. Among other things, that routine disables all the other windows in the application, so you need to replace the DisableTaskWindows/EnableTaskWindows calls with EnableWindow(Owner.Handle, False/True) to just disable the parent form. At this point you can open multiple dialogs, but they can only be closed in last-in, first-out order, because the calls end up being recursive. If that's fine, stop here.
There are two ways to work around that:
Rather than making ShowModal blocking, have StartModal and EndModal routines that have the first bit and last bit of ShowModal's code and call an OnShowModalDone event when the dialog is closed. This is kind of a pain to use, but is relatively easy to code and easy to make stable.
Use the Windows fiber routines to swap out the stack and start a new message loop. This approach is easy to use, because ShowModal is blocking, so you call it like normal. This is the approach we used in Beyond Compare. Don't do it. It's complicated to write, there will be stability issues for non-trivial applications because of incompatibilities with third party code (Windows global message hooks, TWebBrowser, .NET in shell extensions loaded by the browse dialog, etc), and if it's a cross-platform project, the Unix ucontext functions aren't safe to use either.
The common dialogs (TOpenDialog, TColorDialog, etc), have similar restrictions. To make them only disable the parent form you need to override TCommonDialog.TaskModalDialog and replace the DisableTaskWindows/EnableTaskWindows calls there too. They can't be made asynchronous like the regular Delphi dialogs above though, since they're blocking functions provided by Windows (GetOpenFileName, ChooseColor, etc). The only way to allow those to close in any order is to have each dialog run in a dedicated thread. Windows can handle most of the synchronization to do that, as long as you're careful about accessing the VCL objects, but it basically involves rewriting large portions of Dialogs.pas.
If you really want that,
1) use a small, maybe hidden, MainForm and launch just the first childform at startup.
2) launch separate applications instead of Windows in the same process. This is what later Office version use.
Here is a similar StackOverflow question:
Multiple app windows activation not working correctly
In my case I don't try to avoid the MainForm like Craig describes. Instead, I hide the main window and all of my real windows are other non-modal forms. I have been happy with how my application works, but Craig's approach may be simpler.
See my answer on the above question to see code samples for my approach and a few links with good background information.
The first form created in a Delphi application is treated as the main form and the application terminates when this form gets closed. The obvious solution is to have a first form that is not one that gets closed by the user but rather one that is not visible to the user and gets closed only when all other forms have been closed.
I have not tried this, but it should work.
This is too late to be an answer but I bumped into the same problem. The solution I opted for is to extract Application.ExeName and pass it to a function like createProcess or even shellExecute. So, now I have independent applications at the OS Level. I also needed different taskbar buttons for the different instances.

Resources