Best algorithm for syntax highlight (WINAPI) - winapi

I write a program on WINAPI. I must to implement syntax highlight. At this moment the I using following algorithm:
void PaintWords(const char *SearchWord,COLORREF rgb)
{
counter = TabCtrl_GetCurSel(TabControl_hWnd);
ft.chrg.cpMin = 0;
ft.chrg.cpMax = GetWindowTextLength(hWnd);
ft.lpstrText = (LPCSTR)SearchWord; //keyword
do
{
int poe_p = SendMessage(hWnd, EM_FINDTEXTEX, FR_DOWN | FR_WHOLEWORD | FR_MATCHCASE, (LPARAM)&ft);
if(poe_p != -1)
{
int selword = SendMessage(hWnd, EM_EXSETSEL,0,(LPARAM)&ft.chrgText);
ZeroMemory(&chd, sizeof(chd));
chd.cbSize = sizeof(CHARFORMAT);
chd.dwMask = CFM_SIZE | CFM_FACE | CFM_COLOR | CFM_CHARSET;
chd.crTextColor = rgb;
chd.bPitchAndFamily = FW_THIN;
lstrcpy(chd.szFaceName , "Courier New");
SendMessage(hWnd,EM_SETCHARFORMAT,SCF_WORD|SCF_SELECTION,(LPARAM)&chd);
ft.chrg.cpMin = ft.chrgText.cpMax;
}
else
{
break;
}
}while(ft.chrg.cpMin != ft.chrg.cpMax);
}
This code is too slow, because this is not best option, flicker is visible.
I interested in other variants.

I think you need to use double buffering to reduce the flicker. Other than that, you should not use SendMessage (or even PostMessage) to any window (within same thread). Why selection must happen in your syntax-highlighting paint code?
One of the article on double buffer is this.

I have come across this project's RichTextbox, which is used as an xml editor: http://xpathvisualizer.codeplex.com/SourceControl/changeset/view/42057#XPathVisualizer/CustomControls/RichTextBoxEx.cs
it's in C#, but the messages sent are visible.
When using this TextBox, before highlighting the text the BeginUpdateAndSuspendEvents function should be called.
public IntPtr BeginUpdateAndSuspendEvents()
{
// Stop redrawing:
User32.SendMessage(this.Handle, (int) User32.Msgs.WM_SETREDRAW, 0, IntPtr.Zero);
// Stop sending of events:
IntPtr eventMask = User32.SendMessage(this.Handle, User32.Msgs.EM_GETEVENTMASK, 0, IntPtr.Zero);
return eventMask;
}
This function prevents redrawing while you are working on the text, after you finish editing, you should call
public void EndUpdateAndResumeEvents(IntPtr eventMask)
{
// turn on events
User32.SendMessage(this.Handle, User32.Msgs.EM_SETEVENTMASK, 0, eventMask);
// turn on redrawing
User32.SendMessage(this.Handle, User32.Msgs.WM_SETREDRAW, 1, IntPtr.Zero);
NeedRecomputeOfLineNumbers();
this.Invalidate();
}
Double buffering does not solve this problem because it will not stop the paints from occurring, highlighting an editor without disabling the paint event can cause the program to halt for more than 5 minutes depending on the size of the file and the number of words to be highlighted.

Related

WinAPI + Cmake + Aero

I have a CMake project with an executable and a static library (linked to the exe). The library is responsible for implementing the creation of the window (using WinAPI for Windows OS), and the executable contains the main entry point (in this case a simple int main(...) function).
I've been googling for a day but cannot find a way to create a window with Aero support (can maximize by dropping to the top, the title bar is a little bit transparent, etc). I've read the Enabling Visual Styles MSDN article but I'm not sure how I should handle this with CMake. Especially that the window implementation is hidden to the client (since it's implemented in the library).
The windowing code is really basic right now for simplicity. Some of the code will be refactored, the point is not that right now. Here is the (almost) full code for creating the window.
bool WindowsWindow::create(const WindowCreateInfo& info)
{
// register custom window class
{
WNDCLASSEX wnd = { 0 };
wnd.cbSize = sizeof(wnd);
wnd.lpszClassName = CLASS_NAME;
wnd.hInstance = GetModuleHandle(nullptr);
wnd.lpfnWndProc = wndProc;
wnd.style = CS_OWNDC;
wnd.hbrBackground = reinterpret_cast<HBRUSH>(COLOR_WINDOW);
wnd.hCursor = LoadCursor(NULL, IDC_ARROW);
if (RegisterClassEx(&wnd) == 0) {
return false;
}
hInstance = wnd.hInstance;
}
HMONITOR monitor = MonitorFromWindow(nullptr, MONITOR_DEFAULTTOPRIMARY);
MONITORINFO monitorInfo;
monitorInfo.cbSize = sizeof(MONITORINFO);
GetMonitorInfo(monitor, &monitorInfo);
LONG style = 0;
LONG exStyle = WS_EX_APPWINDOW;
int x = CW_USEDEFAULT;
int y = CW_USEDEFAULT;
int width = info.width;
int height = info.height;
if (info.isWindowed) {
style = WS_OVERLAPPED | WS_BORDER | WS_CAPTION;
if (info.hasSysMenu) {
style |= WS_SYSMENU;
}
if (info.allowMinimize) {
style |= WS_MINIMIZEBOX;
}
if (info.allowMaximize) {
style |= WS_MAXIMIZEBOX;
}
// ... positioning, adjusting size, etc.
} else {
style = WS_POPUP;
x = monitorInfo.rcMonitor.left;
y = monitorInfo.rcMonitor.top;
width = monitorInfo.rcMonitor.right - x;
height = monitorInfo.rcMonitor.bottom - y;
}
handle = CreateWindowEx(
exStyle,
CLASS_NAME,
info.title,
style,
x,
y,
width,
height,
HWND_DESKTOP,
nullptr,
hInstance,
nullptr
);
if (!handle) {
return false;
}
running = true;
ShowWindow(handle, SW_SHOW);
return true;
}
The loop is the standard Peek-Translate-Dispatch trio and the WndProc only handles the WM_CLOSE message, otherwise returns with DefWindowProc.
How could I enable the Aero support in this kind of setup?
If the proper manifest file would be the solution, how should I handle it correctly? I mean the client (the executable) should not care that the underlying library is using WinAPI or not
A CMake example would be really helpful
Current solution
I was able to find an example (actually from a Vulkan SDK) that pointed out that I need the WS_THICKFRAME style (a resize border) in order to my window become modern looking (Aero-like).

RestoreCapture FMX - Win32

I took this example of subclassing a Form's HWND as a starting point and then added in jrohde's code from from here that is designed to let you drag a Form by clicking anywhere on it (not on the caption bar). This code fails on the ReleaseCapture()line with this message: E2283 Use . or -> to call '_fastcall TCommonCustomForm::ReleaseCapture()
If i comment that line out the code runs and i can move the form by left mouse don and drag, but i can't let go of it. The mouse gets stuck to the form like flypaper. If i replace the ReleaseCapture() with a ShowMessage i can break out but that is obviously not the way to go...
What do i need to do allow that RestoreCapture() to run? This is Win32 app.
BELOW IS THE CODE i added to the original switch(uMsg) block:
// two int's defined above the switch statement
static int xClick;
static int yClick;
// new case added to the switch
case WM_LBUTTONDOWN:
SetCapture(hWnd);
xClick = LOWORD(lParam);
yClick = HIWORD(lParam);
break;
case WM_LBUTTONUP:
//ReleaseCapture(); // This is the problem spot <------------------------
ShowMessage("Up");
break;
case WM_MOUSEMOVE:
{
if (GetCapture() == hWnd) //Check if this window has mouse input
{
RECT rcWindow;
GetWindowRect(hWnd,&rcWindow);
int xMouse = LOWORD(lParam);
int yMouse = HIWORD(lParam);
int xWindow = rcWindow.left + xMouse - xClick;
int yWindow = rcWindow.top + yMouse - yClick;
SetWindowPos(hWnd,NULL,xWindow,yWindow,0,0,SWP_NOSIZE|SWP_NOZORDER);
}
break;
thanks, russ
From the error message you can derive that the compiler resolves the function ReleaseCapture() to TCommonCustomForm::ReleaseCapture(). But you want to call the Win32 API function ReleaseCapture(). Use ::ReleaseCapture(); instead of ReleaseCapture(); to enforce this.

PrintWindow: screenshot is offset sometimes

I'm taking screenshots of windows using PrintWindow(). This works finde with the following code.
This works most of the time - I'm calling it very often in a continuos loop - but sometimes it fails. I started saving screenshots of the times it fails. Sometimes they are just black, but sometimes the ClientArea of the captured window is somehow offset and only visible on half the picture. Why is that the case?
EDIT:
Is the PrintWindow function guaranteed to work, even when its called ~100times a second? What makes me wonder is, that after every print window I'm actually verifying two pixels which default colors I stored as a COLORREF at startup. The program says they match almost all the time. Still, once I use GetPixel, the returned value from other pixels is simply black or white from time to time (which should never be the case). Once I save the HDC/HBITMAP as a screenshot (I called GdiFlush before), the screenshot is just plain black (which shouldn't be the case either, as I said, I checked two pixels before...).
Well for now, back to the initial question: Is this definitely my fault, or is it possible that PrintWindow just gives random results from time to time, without returning an error?
Ok, this is the NEW CODE:
/* Try printing the window 10times, in case it fails. */
for (int i = 0; i <= NUM_ITERATIONS_PREP; i++) {
releaseSurface();
prepared_HWND = hwnd;
window_dc = GetWindowDC(hwnd);
surface = CreateCompatibleDC(window_dc);
if (surface) {
RECT r;
GetWindowRect(hwnd, &r);
bmp = CreateCompatibleBitmap(window_dc, r.right - r.left, r.bottom - r.top);
if (!ReleaseDC(hwnd, window_dc)) {
writeLog("ReleaseDC failed.", black, true);
}
if (bmp) {
old_surface_bmp = SelectBitmap(surface, bmp);
//InvalidateRect(hwnd, 0, TRUE);
//UpdateWindow(hwnd);
int result = PrintWindow(hwnd, surface, 0);
if (result != 0) {
if (!verify || verifySurface())
break;
else {
writeLog("Surface could not be verified on iteration " + std::to_string(i) + ". Saving screenshot.", black, true);
saveDebugScreenshot();
QThread::msleep(2);
}
} else {
writeLog("PrintWindow() failed.", black, true);
}
}
else {
writeLog("BMP creation failed.", black, true);
}
}
else {
writeLog("HDC creation failed.", black, true);
}
}
And the new RELEASE CODE:
/* If you call prepareSurface(), call this once the surface isn't need anymore. */
void ClientProfile::releaseSurface() {
SelectObject(surface, old_surface_bmp);
DeleteDC(surface);
DeleteObject(bmp);
prepared_HWND = NULL;
}
releaseSurface() is called either at the beginning of prepareSurface() and additionally every time I'm done processing a table (this means its called once too often for every prepareSurface(). Is that a problem?).
Oh and old_surface_bmp, bmp and surface are declared as private class attributes.

Win32: full-screen and hiding taskbar

I have a window, which I SetWindowPos(window, HWND_TOP, 0, 0, GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN), SWP_FRAMECHANGED);
It covers the whole screen, ok, but it takes a while (0.5 sec) to cover the taskbar as well.
Is there a way to come over the taskbar immediately? I found that setting HWND_TOPMOST does it immediately, but it stays above all the other windows, even if I switch the app - this is something I don't want. Also, if I first hide the window and then show it, it somehow forces the window to redraw and covers the taskbar immediately, but it flickers (because of the hiding). Is there another way?
Edit 2. There is even a better way for doing fullscreen, the chromium way, source taken from here:
http://src.chromium.org/viewvc/chrome/trunk/src/ui/views/win/fullscreen_handler.cc?revision=HEAD&view=markup
void FullscreenHandler::SetFullscreenImpl(bool fullscreen, bool for_metro) {
ScopedFullscreenVisibility visibility(hwnd_);
// Save current window state if not already fullscreen.
if (!fullscreen_) {
// Save current window information. We force the window into restored mode
// before going fullscreen because Windows doesn't seem to hide the
// taskbar if the window is in the maximized state.
saved_window_info_.maximized = !!::IsZoomed(hwnd_);
if (saved_window_info_.maximized)
::SendMessage(hwnd_, WM_SYSCOMMAND, SC_RESTORE, 0);
saved_window_info_.style = GetWindowLong(hwnd_, GWL_STYLE);
saved_window_info_.ex_style = GetWindowLong(hwnd_, GWL_EXSTYLE);
GetWindowRect(hwnd_, &saved_window_info_.window_rect);
}
fullscreen_ = fullscreen;
if (fullscreen_) {
// Set new window style and size.
SetWindowLong(hwnd_, GWL_STYLE,
saved_window_info_.style & ~(WS_CAPTION | WS_THICKFRAME));
SetWindowLong(hwnd_, GWL_EXSTYLE,
saved_window_info_.ex_style & ~(WS_EX_DLGMODALFRAME |
WS_EX_WINDOWEDGE | WS_EX_CLIENTEDGE | WS_EX_STATICEDGE));
// On expand, if we're given a window_rect, grow to it, otherwise do
// not resize.
if (!for_metro) {
MONITORINFO monitor_info;
monitor_info.cbSize = sizeof(monitor_info);
GetMonitorInfo(MonitorFromWindow(hwnd_, MONITOR_DEFAULTTONEAREST),
&monitor_info);
gfx::Rect window_rect(monitor_info.rcMonitor);
SetWindowPos(hwnd_, NULL, window_rect.x(), window_rect.y(),
window_rect.width(), window_rect.height(),
SWP_NOZORDER | SWP_NOACTIVATE | SWP_FRAMECHANGED);
}
} else {
// Reset original window style and size. The multiple window size/moves
// here are ugly, but if SetWindowPos() doesn't redraw, the taskbar won't be
// repainted. Better-looking methods welcome.
SetWindowLong(hwnd_, GWL_STYLE, saved_window_info_.style);
SetWindowLong(hwnd_, GWL_EXSTYLE, saved_window_info_.ex_style);
if (!for_metro) {
// On restore, resize to the previous saved rect size.
gfx::Rect new_rect(saved_window_info_.window_rect);
SetWindowPos(hwnd_, NULL, new_rect.x(), new_rect.y(),
new_rect.width(), new_rect.height(),
SWP_NOZORDER | SWP_NOACTIVATE | SWP_FRAMECHANGED);
}
if (saved_window_info_.maximized)
::SendMessage(hwnd_, WM_SYSCOMMAND, SC_MAXIMIZE, 0);
}
}
Edit.
It is probably better to create a fullscreen window as BrendanMcK pointed it out in a comment to this answer, see this link: http://blogs.msdn.com/b/oldnewthing/archive/2005/05/05/414910.aspx ("How do I cover the taskbar with a fullscreen window?")
The new code using the link above would be:
HWND CreateFullscreenWindow(HWND hwnd)
{
HMONITOR hmon = MonitorFromWindow(hwnd,
MONITOR_DEFAULTTONEAREST);
MONITORINFO mi = { sizeof(mi) };
if (!GetMonitorInfo(hmon, &mi)) return NULL;
return CreateWindow(TEXT("static"),
TEXT("something interesting might go here"),
WS_POPUP | WS_VISIBLE,
mi.rcMonitor.left,
mi.rcMonitor.top,
mi.rcMonitor.right - mi.rcMonitor.left,
mi.rcMonitor.bottom - mi.rcMonitor.top,
hwnd, NULL, g_hinst, 0);
}
Old answer below - do not use it, stays only for the record on how NOT to do this.
You have to hide taskbar and menubar to see fullscreen immediately.
Here is the code (uses WTL), call SetFullScreen(true) to go into full screen mode:
template <class T, bool t_bHasSip = true>
class CFullScreenFrame
{
public:
bool m_fullscreen;
LONG m_windowstyles;
WINDOWPLACEMENT m_windowplacement;
CFullScreenFrame()
:
m_fullscreen(false),
m_windowstyles(0)
{ }
void SetFullScreen(bool fullscreen)
{
ShowTaskBar(!fullscreen);
T* pT = static_cast<T*>(this);
if (fullscreen) {
if (!m_fullscreen) {
m_windowstyles = pT->GetWindowLongW(GWL_STYLE);
pT->GetWindowPlacement(&m_windowplacement);
}
}
// SM_CXSCREEN gives primary monitor, for multiple monitors use SM_CXVIRTUALSCREEN.
RECT fullrect = { 0 };
SetRect(&fullrect, 0, 0, GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN));
WINDOWPLACEMENT newplacement = m_windowplacement;
newplacement.showCmd = SW_SHOWNORMAL;
newplacement.rcNormalPosition = fullrect;
if (fullscreen) {
pT->SetWindowPlacement(&newplacement);
pT->SetWindowLongW(GWL_STYLE, WS_VISIBLE);
pT->UpdateWindow();
} else {
if (m_fullscreen) {
pT->SetWindowPlacement(&m_windowplacement);
pT->SetWindowLongW(GWL_STYLE, m_windowstyles);
pT->UpdateWindow();
}
}
m_fullscreen = fullscreen;
}
void ShowTaskBar(bool show)
{
HWND taskbar = FindWindow(_T("Shell_TrayWnd"), NULL);
HWND start = FindWindow(_T("Button"), NULL);
if (taskbar != NULL) {
ShowWindow(taskbar, show ? SW_SHOW : SW_HIDE);
UpdateWindow(taskbar);
}
if (start != NULL) {
// Vista
ShowWindow(start, show ? SW_SHOW : SW_HIDE);
UpdateWindow(start);
}
}
};
You also have to add some code to WM_CLOSE message:
case WM_CLOSE:
ShowTaskBar(true);
There is one caveat with this solution, if your application crashes or is killed through task manager, then user losses taskbar on his system permanently! (unless he runs your application again, goes into fullscreen and exits, then he will see the taskbar again).
Earlier in my answer I pointed to "atlwince.h" but that function worked only on Windows CE, the one I pasted above works fine with XP, Vista and 7.
Yup, HWND_TOPMOST does it for me.
Here is a section of code that makes full-screen work well (and quick) for me:
bool enterFullscreen(HWND hwnd, int fullscreenWidth, int fullscreenHeight, int colourBits, int refreshRate) {
DEVMODE fullscreenSettings;
bool isChangeSuccessful;
RECT windowBoundary;
EnumDisplaySettings(NULL, 0, &fullscreenSettings);
fullscreenSettings.dmPelsWidth = fullscreenWidth;
fullscreenSettings.dmPelsHeight = fullscreenHeight;
fullscreenSettings.dmBitsPerPel = colourBits;
fullscreenSettings.dmDisplayFrequency = refreshRate;
fullscreenSettings.dmFields = DM_PELSWIDTH |
DM_PELSHEIGHT |
DM_BITSPERPEL |
DM_DISPLAYFREQUENCY;
SetWindowLongPtr(hwnd, GWL_EXSTYLE, WS_EX_APPWINDOW | WS_EX_TOPMOST);
SetWindowLongPtr(hwnd, GWL_STYLE, WS_POPUP | WS_VISIBLE);
SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, fullscreenWidth, fullscreenHeight, SWP_SHOWWINDOW);
isChangeSuccessful = ChangeDisplaySettings(&fullscreenSettings, CDS_FULLSCREEN) == DISP_CHANGE_SUCCESSFUL;
ShowWindow(hwnd, SW_MAXIMIZE);
return isChangeSuccessful;
}
Note that this will change the resolution if you tell it the wrong settings. This is what I usually want, but if you don't like that, you can find out your resolution by using (where mainWindow is returned from something like CreateWindow() or CreateWindowEx()):
windowHDC = GetDC(mainWindow);
fullscreenWidth = GetDeviceCaps(windowHDC, DESKTOPHORZRES);
fullscreenHeight = GetDeviceCaps(windowHDC, DESKTOPVERTRES);
colourBits = GetDeviceCaps(windowHDC, BITSPIXEL);
refreshRate = GetDeviceCaps(windowHDC, VREFRESH);
When you want to get out of full-screen you do something like this:
bool exitFullscreen(HWND hwnd, int windowX, int windowY, int windowedWidth, int windowedHeight, int windowedPaddingX, int windowedPaddingY) {
bool isChangeSuccessful;
SetWindowLongPtr(hwnd, GWL_EXSTYLE, WS_EX_LEFT);
SetWindowLongPtr(hwnd, GWL_STYLE, WS_OVERLAPPEDWINDOW | WS_VISIBLE);
isChangeSuccessful = ChangeDisplaySettings(NULL, CDS_RESET) == DISP_CHANGE_SUCCESSFUL;
SetWindowPos(hwnd, HWND_NOTOPMOST, windowX, windowY, windowedWidth + windowedPaddingX, windowedHeight + windowedPaddingY, SWP_SHOWWINDOW);
ShowWindow(hwnd, SW_RESTORE);
return isChangeSuccessful;
}
I set my code to change between full-screen and windowed mode using a hotkey, and I keep the windowed mode variables as global, so that when changing to windowed mode, it stays put.
This code also has the advantage of running in the equivalent of "exclusive mode" (I'm using XP, and haven't tried it on the newer versions of windows), which means it'll be much, much faster. Let me know if I've made any mistakes from condensing the code (from my much bigger code).
Raymond Chen describes the "correct" way to do this at his blog:
https://devblogs.microsoft.com/oldnewthing/20100412-00/?p=14353
Fiddling with the task bar window explicitly is not recommended behaviour.
Here's the latest unbroken link to Raymond Chen answer.
Since MSDN/Microsoft keeps breaking links I'll paste below for posterity:
For some reason, people think too hard. If you want to create a fullscreen window that covers the taskbar, just create a fullscreen window and the taskbar will automatically get out of the way. Don't go around hunting for the taskbar and poking it; let it do its thing.
As always, start with the scratch program and add the following:
HWND CreateFullscreenWindow(HWND hwnd)
{
HMONITOR hmon = MonitorFromWindow(hwnd,
MONITOR_DEFAULTTONEAREST);
MONITORINFO mi = { sizeof(mi) };
if (!GetMonitorInfo(hmon, &mi)) return NULL;
return CreateWindow(TEXT("static"),
TEXT("something interesting might go here"),
WS_POPUP | WS_VISIBLE,
mi.rcMonitor.left,
mi.rcMonitor.top,
mi.rcMonitor.right - mi.rcMonitor.left,
mi.rcMonitor.bottom - mi.rcMonitor.top,
hwnd, NULL, g_hinst, 0);
}
void OnChar(HWND hwnd, TCHAR ch, int cRepeat)
{
if (ch == TEXT(' ')) {
CreateFullscreenWindow(hwnd);
}
}
HANDLE_MSG(hwnd, WM_CHAR, OnChar);
Note that this sample program doesn't worry about destroying that fullscreen window or preventing the user from creating more than one. It's just a sample. The point is seeing how the CreateFullScreenWindow function is written.
We use the MonitorFromWindow function to figure out which monitor we should go fullscreen to. Note that in a multiple monitor system, this might not be the same monitor that the taskbar is on. Fortunately, we don't have to worry about that; the taskbar figures it out.
I've seen people hunt for the taskbar window and then do a ShowWindow(hwndTaskbar, SW_HIDE) on it. This is nuts for many reasons.
First is a mental exercise you should always use when evaluating tricks like this: "What if two programs tried this trick?" Now you have two programs both of which think they are in charge of hiding and showing the taskbar, neither of which is coordinating with the other. The result is a mess. One program hides the taskbar, then the other does, then the first decides it's finished so it unhides the taskbar, but the second program wasn't finished yet and gets a visible taskbar when it thought it should be hidden. Things only go downhill from there.
Second, what if your program crashes before it gets a chance to unhide the taskbar? The taskbar is now permanently hidden and the user has to log off and back on to get their taskbar back. That's not very nice.
Third, what if there is no taskbar at all? It is common in Terminal Server scenarios to run programs by themselves without Explorer (archived). In this configuration, there is no Explorer, no taskbar. Or maybe you're running on a future version of Windows that doesn't have a taskbar, it having been replaced by some other mechanism. What will your program do now?
Don't do any of this messing with the taskbar. Just create your fullscreen window and let the taskbar do its thing automatically.
I believe the taskbar will get out of the way when its shell hook tells it about a "rude app", this might take a little while.
What if you start out with the window HWND_TOPMOST and make it not top most after 1 second?
Right click on the taskbar
choose Properties
uncheck the checkbox that says "Keep the taskbar on top of other windows".
The taskbar belongs to the user, It's up to them to care about having it take 1/2 second to auto-hide when you app goes full screen. If they want to change that behavior then they can change it.
If you are working in an embedded system, then you may have a legitimate reason to hide the taskbar. But in that case, there's no reason not to simply configure the taskbar to not always be on top. You could also have a look at SystemParametersInfo if you want to change some of these settings in your code.

MouseDown and then MouseUp doesn't work

I am trying to redirect mouse inputs on my Windows 7 application to some other window.
If I do this when I get WM_LBUTTONUP, it works (where MouseDown and MouseUp are SendInput functions in Win api):
SetForegroundWindow( other window );
SetCursorPos( somewhere on the window );
MouseDown();
MouseUp();
SetCursorPos( back );
SetForegroundWindow( main window );
But I don't want to only do mouse releases, I want to be able to capture all mouse stuff, including movements and dragging.
So this is next logical thing to do but it doesn't work:
WM_LBUTTONDOWN:
Do everything like before without MouseUp()
WM_LBUTTONUP:
Do everything like before without MouseDown()
This doesn't even work for regular clicks. I can't figure out why.
Can anybody help?
Mouse buttons are funky. When it gets an down then up, at some level those are converted to a click (and I think at some point the mouse up gets eaten, but I may not be recalling that correctly).
It could be any number of things, but if the other windows is (or is not) converting the buttondown/up to mouse clicks, it could be confusing your code.
I suggest you print a lot of debugging info and try to figure out exactly what the system is doing.
It might be worth looking at the SendMessage/PostMessage P/Invoke calls, and sending the messages directly to the window of the other application. You need to do some translation on the parameters so that the co-ordinates of mouse events tie up with what you want them to in the other application, but it's not a big deal to do that...
Edit -> I dug out some code where I have done this before... This is from a window which appears over the top of a tree view and replaces the default windows tooltip for that tree view.
private IntPtr _translate(IntPtr LParam)
{
// lparam is currently in client co-ordinates, and we need to translate those into client co-ordinates of
// the tree view we're attached to
int x = (int)LParam & 0xffff;
int y = (int)LParam >> 16;
Point screenPoint = this.PointToScreen(new Point(x, y));
Point treeViewClientPoint = _tv.PointToClient(screenPoint);
return (IntPtr)((treeViewClientPoint.Y << 16) | (treeViewClientPoint.X & 0xffff));
}
const int MA_NOACTIVATE = 3;
protected override void WndProc(ref Message m)
{
switch ((WM)m.Msg)
{
case WM.LBUTTONDBLCLK:
case WM.RBUTTONDBLCLK:
case WM.MBUTTONDBLCLK:
case WM.XBUTTONDBLCLK:
{
IntPtr i = _translate(m.LParam);
_hide();
InteropHelper.PostMessage(_tv.Handle, m.Msg, m.WParam, i);
return;
}
case WM.MOUSEACTIVATE:
{
m.Result = new IntPtr(MA_NOACTIVATE);
return;
}
case WM.MOUSEMOVE:
case WM.MOUSEHWHEEL:
case WM.LBUTTONUP:
case WM.RBUTTONUP:
case WM.MBUTTONUP:
case WM.XBUTTONUP:
case WM.LBUTTONDOWN:
case WM.RBUTTONDOWN:
case WM.MBUTTONDOWN:
case WM.XBUTTONDOWN:
{
IntPtr i = _translate(m.LParam);
InteropHelper.PostMessage(_tv.Handle, m.Msg, m.WParam, i);
return;
}
}
base.WndProc(ref m);
}

Resources