Making a corner of the desktop activate screensaver - c#

I am trying to write a simple application to activate my screensaver when the mouse in at the top right corner of the screen. I have found an answer to controlling the screensaver from C# however I am having trouble working out how to do a "hot corner" type check for the mouse position. This is the only part I am stuck with, any help would be appreciated.
This Activates the screensaver
[DllImport("user32.dll", EntryPoint = "GetDesktopWindow")]
private static extern IntPtr GetDesktopWindow();
[DllImport("user32.dll")]
private static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, int wParam, int lParam);
private const int SC_SCREENSAVE = 0xF140;
private const int WM_SYSCOMMAND = 0x0112;
public static void SetScreenSaverRunning()
{
SendMessage(GetDesktopWindow(), WM_SYSCOMMAND, SC_SCREENSAVE, 0);
}

You could use the System.Windows.Form.Screen class to get the current resolution (take a look at this answer). Then use Cursor.Position.Property to determine where the cursor is currently located (i.e. is it within the boundaries of some predefined rectangle that should activate it).

I have made the exact same thing, only it loads in the top left. What I did was just make the form size 1px by 1px with no border, and just activate the screensaver when the mouse stays over the form for a second. Doing it this way requires that you find all ways to keep the form on top of everything.
Another option would be mouse hooking and just watching for (0,0) mouse position, or for the top right - (0, screen.width)

You could also try ScrHots from Lucian Wischik. It's freeware and does exactly what you need, and also has hot-corners for "never activate the screensaver" capability. All four corners can be programmed to do either function. I've used this one for years, and it works great.
http://www.wischik.com/scr/savers.html (ScrHots3, under the "Utilities" section)
Hope this helps someone.

Related

Headaches with GetWindowRect GetWindowPlacement DwmGetWindowAttribute

I'm a writing window management app in c# winforms to reposition other windows on the desktop. My issue came when I started using user32.dll calls to get the other windows size and position:
[DllImport("user32.dll")]
public static extern bool GetWindowRect(IntPtr hWnd, out Rect lpRect);
There's 2 problems with this method.
Most (but not all) windows the coordinates and size are off by 7 pixels (thanks dropshadow!), So for example a window at the left of the screen would be actually at -7 instead of 0.
Minimized windows are reporting -32000 coordinates.
To solve problem 2 I tried to use:
[DllImport("user32.dll")]
public static extern bool GetWindowPlacement(IntPtr hWnd, out WindowPlacement lpwndpl);
Using this method we can pull from the WindowPlacment struct the windows normal size when restored, even while it is minimized. Great! But it still gives the weird 7 pixel offset from the dropshadow... not so great.
In order to pull the actual size of the window (Problem 1) we can use:
[DllImport("dwmapi.dll")]
public static extern int DwmGetWindowAttribute(IntPtr hwnd, int dwAttribute, out Rect pvAttribute, int cbAttribute);
By getting the EXTENDED_FRAME_BOUNDS attribute we can pull the correct dimensions of the window without the drop shadow. But... if the window is minimized we still get coordinates in outer space!
And this is before even trying to solve the problem of scaled windows vs physical screen coordinates.
At the moment the only solution I can think of is to unminimize a window compare it's size with GetWindowRect to the GetWindowPlacement version and store the difference to take into account when moving and repositioning it. But to say this is a horrible workaround is an understatement.
Surely there's a better way?

MonitorFromWindow(DefaultToNearest) doesn't work during drag

I'm using the Windows API method MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST) as part of some overridden maximize functionality in my WPF application. One issue we've had with it is that the "nearest" window does not updating during drag operations (triggered by DragMove on the Window instance).
Suppose you drag the window between two screens of differing resolution and trigger the Aero Snap functionality on the second screen. This triggers a query on the window size (message WM_GETMINMAXINFO). Using MonitorFromWindow in this scenario returns the wrong screen. It's as if the data used by MONITOR_DEFAULTTONEAREST is not updated until the drag operation completes, and that doesn't complete until the resize function triggered by the Aero Snap completes. Is there some way to flush the current window position before answering the WM_GETMINMAXINFO query?
Since snapping is based on the mouse position, a solution to the problem would be to use GetCursorPos to get the current mouse position. Then pass that point to MonitorFromPoint to obtain the handle for the monitor that currently contains the mouse pointer.
A simple example:
[DllImport("User32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetCursorPos(ref Point lpPoint);
public const int MONITOR_DEFAULTTONEAREST = 2;
[DllImport("User32.dll")]
public static extern IntPtr MonitorFromPoint(Point pt, UInt32 dwFlags);
public IntPtr GetCurrentMonitor()
{
Point p = new Point(0,0);
if (!GetCursorPos(ref p))
{
// Decide what to do here.
}
IntPtr hMonitor = MonitorFromPoint(p, MONITOR_DEFAULTTONEAREST);
// validate hMonitor
return hMonitor;
}

Cannot Make GetWindowRect() API Call To Work Properly

I require the ability to get the height of the on screen keyboard for Windows 8.1, "TabTip.exe." So far I've managed to open and close it at will, but now I also need to get it's height so I can compensate for it in my app. I have TextBox controls near the very bottom of the Window that get covered up by the keyboard.
All attempts to utilize the Win API call "GetWindowRect" have failed.
Code placed just inside the beginning of the class definition:
private const string OnScreenKeyboardName = "TabTip";
DllImport("user32.dll")]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool GetWindowRect(HandleRef hWnd, ref RECT lpRect);
[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
public int Left; // x position of upper-left corner
public int Top; // y position of upper-left corner
public int Right; // x position of lower-right corner
public int Bottom; // y position of lower-right corner
}
code placed inside one of the event handlers in the Window:
RECT rct = new RECT();
if (Process.GetProcessesByName(OnScreenKeyboardName).Length > 0)
{
Process[] Processes = Process.GetProcessesByName(OnScreenKeyboardName);
foreach (Process pOnScreenKeyboard in Processes)
{
if (!GetWindowRect(new HandleRef(this, pOnScreenKeyboard.Handle), ref rct))
{
MessageBox.Show("ERROR");
return;
}
MessageBox.Show(rct.ToString());
}
}
Consistent with most examples, I had originally been using a call to "FindWindow" to get the handle for the TabTip.exe Window. That seemed to work great for a while, but it stopped working all of a sudden within the last few days, and so I switched to "Process.FindByName..."
My test case involves placing the code (second part) above into the Window's "MouseMove" event handler. Then I make sure the on screen keyboard is showing, and then I move the mouse. This causes the event to fire and then it always shows the "ERROR" MessageBox, which indicates that "GetWindowRect" returns false (or has some kind of error?
I've spent a lot of time on Google searches, p/invoke, etc. This is frustrating because there seem to be very few examples of how to properly do this. And it seems there is some new thing called a HandleRef (am I using that properly? - there are basically no examples for that either!!!)
I really need to get this working. Can someone please tell me where I'm going wrong? Thanks!
You are passing the process handle (pOnScreenKeyboard.Handle) to GetWindowRect where GetWindowRect expects a window handle (HWND). Finding the process isn't sufficient - a process can create many windows, so you need to find the onscreen keyboard's window handle. You can try using pOnScreenKeyboard.MainWindowHandle, but from this post, you might find that it's null. You said you had a previous solution using FindWindow. I would go back to that and figure out why it stopped working.

"Hiding" System Cursor

BACKGROUND:
I'm trying to create a "mouse hiding" application that hides the user's mouse from the screen after a set amount of time.
I've tried many things, and using SetCursor only hides the mouse from the current application, mine must be able to sit in the tray (for example) and still function.
I think I've found a solution with SetSystemCursor except for one problem.
MY PROBLEM:
I need to be able to capture any kind of mouse cursor, and replace the exact same kind of mouse cursor.
When replacing the mouse, I need to provide the id of the type of mouse I'd like to replace with the mouse referenced by the handle, but none of the functions I'm using provide me with the copied mouse's id (or type).
MY QUESTION:
Would it be sufficient to continue doing it this way, but move the mouse to 0,0 first, hiding it, and moving it back to it's original location upon un-hiding? (Unhiding is accomplished by simply moving the mouse)
Would a mouse at 0,0 always be an OCR_NORMAL mouse? (The standard arrow.)
If not, how could the mouse type/id be found to enable me to replace the proper mouse with the proper handle?
SOURCE:
[DllImport("user32.dll")]
public static extern IntPtr LoadCursorFromFile(string lpFileName);
[DllImport("user32.dll")]
public static extern bool SetSystemCursor(IntPtr hcur, uint id);
[DllImport("user32.dll")]
static extern bool GetCursorInfo(out CURSORINFO pci);
[StructLayout(LayoutKind.Sequential)]
public struct POINT
{
public Int32 x;
public Int32 y;
}
[StructLayout(LayoutKind.Sequential)]
struct CURSORINFO
{
public Int32 cbSize; // Specifies the size, in bytes, of the structure.
// The caller must set this to Marshal.SizeOf(typeof(CURSORINFO)).
public Int32 flags; // Specifies the cursor state. This parameter can be one of the following values:
// 0 The cursor is hidden.
// CURSOR_SHOWING The cursor is showing.
public IntPtr hCursor; // Handle to the cursor.
public POINT ptScreenPos; // A POINT structure that receives the screen coordinates of the cursor.
}
private POINT cursorPosition;
private IntPtr cursorHandle;
private bool mouseVisible = false;
private const uint OCR_NORMAL = 32512;
//Get the current mouse, so we can replace it once we want to show the mouse again.
CURSORINFO pci;
pci.cbSize = Marshal.SizeOf(typeof(CURSORINFO));
GetCursorInfo(out pci);
cursorPosition = pci.ptScreenPos;
cursorHandle = CopyIcon(pci.hCursor);
//Overwrite the current normal cursor with a blank cursor to "hide" it.
IntPtr cursor = LoadCursorFromFile(#"./Resources/Cursors/blank.cur");
SetSystemCursor(cursor, OCR_NORMAL);
mouseVisible = false;
//PROCESSING...
//Show the mouse with the mouse handle we copied earlier.
bool retval = SetSystemCursor(cursorHandle, OCR_NORMAL);
mouseVisible = true;
One application can't affect another applications cursor. You'd have to write a mouse driver of some sort in order to do this.
I found a good workaround for hiding system cursor temporarily that doesn't involve screwing around with setsystemcursor().
SetSystemCursor() is dangerous, because if the app crashes or otherwise throws a bug, the cursor will be changed permanently until the next reboot.
Instead, I implemented a transparent window over the whole desktop, and that window hides the cursor when needed. The method to use is ShowCursor from Win32.
The transparent window can be something like this:
http://www.codeproject.com/Articles/12597/OSD-window-with-animation-effect-in-C
[DllImport("user32.dll")]
static extern int ShowCursor(bool bShow);
ShowCursor(false);

Send user input through a windows form

I am looking for a way to pass mouse events through a winform without using Form.TransparencyKey.
If there is no simple way to do this, is there a way to send a mouse event to a given window handle using Win32 API?
Edit
By pass through the winform I do not mean to a parent window, I mean to other applications that reside behind mine.
This may sound overkill, as I saw SLaks's answer..
You would need
The handle of the Window using Handle property
Use pinvoke on the SendMessage Win32API
One of the parameters to SendMessage is WM_LBUTTONDOWN
Here's a declaration for the SendMessage
[DllImport("user32")] static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);
Here's the constants used:
public const int WM_LBUTTONDOWN = 0x201;
public const int WM_LBUTTONUP = 0x202;
Typical Invocation:
SendMessage(someWindow.Handle, WM_LBUTTONDOWN, IntPtr.Zero, IntPtr.Zero);
SendMessage(someWindow.Handle, WM_LBUTTONUP, IntPtr.Zero, IntPtr.Zero);
The invocation is an example of how to send a mouse left-click to a specified window.
I used pinvoke.net to obtain the correct API.
Hope this helps,
Best regards,
Tom.
The answer is actually much easier than I thought it would be.
This SO answer got me where I needed to be:
Transparent Window (or Draw to screen) No Mouse Capture
Also found what looks like a c++ implementation if you want some working code:
Transparent Window (or Draw to screen) No Mouse Capture

Categories