It takes some time for my program to finish computation, so I would like to run it, read some web pages meanwhile, and when the screen flashes (notification of finished computation), I would get back to my program.
The only missing part is -- how to flash entire screen in C#? I use WPF if this matters.
Please note -- my program is not visible, the other program (web browser for example) takes entire screen (that is the point of the problem, because otherwise, I wouldn't need any notification at all).
Flash = blink.
my first approach would be: on completion of the computation have your program open a new topmost window with transparent background and set it to some color (white) for some brief intervals and close the window again. mind you, while the window is on top you'll not be able to interact with underlying windows during the flashing because the window will eat those events. Alternatively, you could do what most other windows applications (like outlook or messenger) do: display a brief notification box that is clickable to get you to the associated application (your program).
i think a more 'normal' practice would be to install the app as a sys tray icon - then you can change that upon any status change.
[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern Int16 FlashWindowEx(ref FLASHWINFO pwfi);
[System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)]
public struct FLASHWINFO {
public UInt32 cbSize;
public IntPtr hwnd;
public UInt32 dwFlags;
public UInt32 uCount;
public UInt32 dwTimeout;
}
public const UInt32 FLASHW_STOP = 0;
public const UInt32 FLASHW_CAPTION = 1;
public const UInt32 FLASHW_TRAY = 2;
public const UInt32 FLASHW_ALL = 3;
public void Flash() {
FLASHWINFO flashInfo = new FLASHWINFO();
flashInfo.cbSize = (uint)System.Runtime.InteropServices.Marshal.SizeOf(flashInfo);
flashInfo.hwnd = this.Handle; // get the window handle
flashInfo.dwFlags = FLASHW_TIMERNOFG | FLASHW_ALL;
flashInfo.uCount = UInt32.MaxValue;
flashInfo.dwTimeout = 0;
FlashWindowEx(ref flashInfo);
}
I don't think that you can technically flash your screen with WPF. Maybe with a Win32 function. But would it be a possibility to make a screenshot and show a Windows that shows a modified version of that screenshot? This window would have to be declared as TopMost and cover your screen and your image could be modified by increasing the alpha channel over the time.
Edit: OK, I think I misunderstood "flash". If you just want to show a flashing rectangle with one color have a look at the thread which Mamta Dalal posted.
Related
I've got a console application that executes my code without user interaction. If the user clicks within the console window, on purpose or on accident, all execution stops.
This has something to do with copying text from the console window. The only way for the application to start executing again is if the user selects text and then right-clicks on the console window, copying it to the clipboard.
To see this in action, create a console application and add the following code.
class Program
{
static void Main(string[] args)
{
var task = Task.Run(async () =>
{
int i = 0;
while (true)
{
Console.WriteLine(i++);
await Task.Delay(1000);
}
});
Console.ReadLine();
}
}
When you click on the console window, the Task thread stops executing. This is not desirable behavior at all, and I want to prevent this from happening in my console application.
How can I prevent this? None of the properties/events on the console window have anything to do with controlling this behavior, as far as I can see.
As you can see, when i'm click within window appear cursor. When i press any key - cursor gone and app continue working
This happens if you have Quick Edit Mode enabled on the console window. If you right-click on the title bar and select Properties, then select the Options tab, you can check to see if Quick Edit Mode is enabled. If you disable Quick Edit Mode, then the scrolling doesn't stop when you click in the window.
The reason scrolling stops is because a mouse clicked in the window is used to select text.
You can disable Quick Edit Mode on the console in your program, but doing so requires calling the GetConsoleMode and SetConsoleMode API functions. Here's how you would do it:
[DllImport("kernel32.dll", SetLastError=true)]
public static extern IntPtr GetConsoleWindow();
[DllImport("kernel32.dll", SetLastError=true)]
public static extern bool GetConsoleMode(
IntPtr hConsoleHandle,
out int lpMode);
[DllImport("kernel32.dll", SetLastError=true)]
public static extern bool SetConsoleMode(
IntPtr hConsoleHandle,
int ioMode);
/// <summary>
/// This flag enables the user to use the mouse to select and edit text. To enable
/// this option, you must also set the ExtendedFlags flag.
/// </summary>
const int QuickEditMode = 64;
// ExtendedFlags must be combined with
// InsertMode and QuickEditMode when setting
/// <summary>
/// ExtendedFlags must be enabled in order to enable InsertMode or QuickEditMode.
/// </summary>
const int ExtendedFlags = 128;
void DisableQuickEdit()
{
IntPtr conHandle = GetConsoleWindow();
int mode;
if (!GetConsoleMode(conHandle, out mode))
{
// error getting the console mode. Exit.
return;
}
mode = mode & ~(QuickEditMode | ExtendedFlags);
if (!SetConsoleMode(conHandle, mode))
{
// error setting console mode.
}
}
void EnableQuickEdit()
{
IntPtr conHandle = GetConsoleWindow();
int mode;
if (!GetConsoleMode(conHandle, out mode))
{
// error getting the console mode. Exit.
return;
}
mode = mode | (QuickEditMode | ExtendedFlags);
if (!SetConsoleMode(conHandle, mode))
{
// error setting console mode.
}
}
If you go down this route, it's probably a good idea to save the original console mode setting when your program starts, and restore it when your program exits. So at startup:
GetConsoleMode(GetConsoleWindow(), ref saveConsoleMode);
and when your program terminates:
SetConsoleMode(GetConsoleWindow(), saveConsoleMode);
With appropriate error handling, of course. You wouldn't want to restore the console mode if the call to GetConsoleMode failed.
I just saw that this answer linked in the comments of OP's question contained what I found by myself. I will keep my answer because people might not see it, just like me, and it would spare them a lot of time.
Jim's answer did not work for me, I couldn't figure out why.
I dug around and found a solution that works, so I'll share my findings, hopefully helping someone in the same situation.
The problem was with the handle that I got from GetConsoleWindow(), it gave a Win32 error (0x6) where the handle is invalid when I tried to use it. The call to SetConsoleMode() did nothing.
To get a working handle, I used GetStdHandle() to get the Input handle for the console. Add this to Jim's code :
public const int STD_INPUT_HANDLE = -10;
[DllImport("Kernel32.dll", SetLastError = true)]
public static extern IntPtr GetStdHandle(int nStdHandle);
Then replace GetConsoleWindow() by GetStdHandle(STD_INPUT_HANDLE) in DisableQuickEdit() and EnableQuickEdit() in Jim's code.
After calling DisableQuickEdit(), the selection is disabled in the console.
Thanks Jim !
Background:
I have a requirement to create a dimming effect on another monitor. I think I solved it by using a WPF Window that takes up the entire screen dimensions with Topmost and AllowsTransparency = True. It has an inner black glow effect and has the style WS_EX_TRANSPARENT | WS_EX_TOOLWINDOW applied to it (among other things) to allow users to click through to the apps behind it.
I monitor for EVENT_OBJECT_REORDER events in Windows and call SetWindowPos to force the Topmost state above other Topmost windows. It seems to work well so far in my proof of concept testing.
The problem I found was this dimming (window) would cover the task bar, but not if I click the Start Menu. I'm currently testing with Windows 10. If I click the Start Menu, it causes the Start Menu and Taskbar to appear above the dimming (window). I wanted everything to remain dim, always.
I solved this issue by setting uiAccess=true in the app manifest, generating a self-signed cert, and copying the exe over to "c:\program files*". This allows me to force a Topmost state for my window, even above the Start Menu.
My questions:
Is there a way to position a window over the Start Menu without uiAccess? Or even another way to force dimness to a screen without using a window (but not dependent on monitor drivers or hardware capabilities)?
If not, what considerations do I need to keep in mind when distributing a WPF app (via a WiX setup project or something similar) that is to bypass UIPI restrictions with uiAccess=True? Can I simply install my self signed cert during the setup process? Will the user run into any additional hurdles? Will I, as a developer, run into any additional hurdles while building this (aside from what I've already mentioned)?
Thank you!
I monitor for EVENT_OBJECT_REORDER events
You are using SetWinEventHook(). This scenario fails the classic "what if two programs do this" bracket. Raymond Chen discussed this pretty well in this blog post, giving your approach a dedicated post.
This is a lot more common than you might assume. Every Windows machine has a program that does this for example, run Osk.exe, the on-screen keyboard program. Interesting experiment, I predict it will flicker badly for a while but assume it will eventually give up. Not actually sure it does, last time I tried this was at Vista time and it wouldn't, please let us know.
Fairly sure you will conclude that this isn't the right way to go about it so uiAccess is moot as well. You needed it here to bypass UIPI and make SetWindowPos() work. An aspect of UAC that blocks attempts by a program to hijack an elevated program's capabilities. Covering the Start window qualifies as a DOS attack. Bigger problem here is that your self-signed certificate isn't going to work, you'll have to buy a real one. Sets you back several hundred dollars every ~7 years.
Controlling monitor brightness with software isn't that easy to do correctly. Everybody reaches for SetDeviceGammaRamp() and that is what you should do as well. The MSDN docs will give you plenty of FUD but afaik every mainstream video adapter driver implements it. It was popular in games. One unavoidable limitation is that it is only active for the desktop in which your program runs. So not for the secure desktop (screen saver and Ctrl+Alt+Del) and not for other login sessions unless they start your program as well.
WMI is too flaky to consider. Not so sure why it fails so often, I assume it has something to do with the often less-than-stellar I2C interconnect between the video adapter and the monitor. Or laptops that want to control brightness with an Fn keystroke, that feature always wins. Or the Windows feature that automatically adjusts brightness based on ambient light, invariably the more desirable way to do this and a hard act to follow.
Most common outcome is likely to be a shrug at your program and a curse of the user at the clumsy monitor controls. But he'll fiddle with it and figure it out. Sorry.
This won't answer anything about uiAccess=true, but...
Dimming the Screen
As an alternative way to dim the screen, you could try using SetDeviceGammaRamp to dim all screens at once (if that's desired).
For example, take the following helper class:
/// <summary> Allows changing the gamma of the displays. </summary>
public static class GammaChanger
{
/// <summary>
/// Retrieves the current gamma ramp data so that it can be restored later.
/// </summary>
/// <param name="gamma"> [out] The current gamma. </param>
/// <returns> true if it succeeds, false if it fails. </returns>
public static bool GetCurrentGamma(out GammaRampRgbData gamma)
{
gamma = GammaRampRgbData.Create();
return GetDeviceGammaRamp(GetDC(IntPtr.Zero), ref gamma);
}
public static bool SetGamma(ref GammaRampRgbData gamma)
{
// Now set the value.
return SetDeviceGammaRamp(GetDC(IntPtr.Zero), ref gamma);
}
public static bool SetBrightness(int gamma)
{
GammaRampRgbData data = new GammaRampRgbData
{
Red = new ushort[256],
Green = new ushort[256],
Blue = new ushort[256]
};
int wBrightness = gamma; // reduce the brightness
for (int ik = 0; ik < 256; ik++)
{
int iArrayValue = ik * (wBrightness + 128);
if (iArrayValue > 0xffff)
{
iArrayValue = 0xffff;
}
data.Red[ik] = (ushort)iArrayValue;
data.Green[ik] = (ushort)iArrayValue;
data.Blue[ik] = (ushort)iArrayValue;
}
return SetGamma(ref data);
}
[DllImport("gdi32.dll")]
private static extern bool SetDeviceGammaRamp(IntPtr hdc, ref GammaRampRgbData gammaRgbArray);
[DllImport("gdi32.dll")]
private static extern bool GetDeviceGammaRamp(IntPtr hdc, ref GammaRampRgbData gammaRgbArray);
[DllImport("user32.dll")]
private static extern IntPtr GetDC(IntPtr hWnd);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct GammaRampRgbData
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 256)]
public UInt16[] Red;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 256)]
public UInt16[] Green;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 256)]
public UInt16[] Blue;
/// <summary> Creates a new, initialized GammaRampRgbData object. </summary>
/// <returns> A GammaRampRgbData. </returns>
public static GammaRampRgbData Create()
{
return new GammaRampRgbData
{
Red = new ushort[256],
Green = new ushort[256],
Blue = new ushort[256]
};
}
}
}
Combined with the following in a static void Main(), and the program will change the brightness until the user exits the application:
GammaChanger.GammaRampRgbData originalGamma;
bool success = GammaChanger.GetCurrentGamma(out originalGamma);
Console.WriteLine($"Originally: {success}");
success = GammaChanger.SetBrightness(44);
Console.WriteLine($"Setting: {success}");
Console.ReadLine();
success = GammaChanger.SetGamma(ref originalGamma);
Console.WriteLine($"Restoring: {success}");
Console.ReadLine();
Do note however, that this is applying a global solution to a local problem
If you do go this route, I'd suggest really making sure that you're restoring the user's gamma before exiting, otherwise they'll be left with a less than steller experience that your app crashed and the screen is no permanently dimmed.
Sources:
Discussion of the usage of SetGammaRamp, which is where a bulk of the algorithm comes from
An alternative implementation of the above solution.
As a fun office project we are building a cool transitional background Winform's app to replace the standard windows desktop background.
One of the challenges is that we need our WinForm window to sit on top of the desktop background and icons but not the taskbar.
Is there some way to precisely adjust the Z-Index of a winform window so that it sits on top of the windows desktop but still allows the taskbar and other windows to sit on top of it?
Thank you for the assistance in getting this working. The following worked for us.
[DllImport("user32.dll", EntryPoint = "SetWindowPos")]
public static extern IntPtr SetWindowPos(IntPtr hWnd, int hWndInsertAfter, int x, int Y, int cx, int cy, int wFlags);
const short SWP_NOMOVE = 0X2;
const short SWP_NOSIZE = 1;
const short SWP_NOZORDER = 0X4;
const int SWP_SHOWWINDOW = 0x0040;
Usage as follows.
// Our desktop is the top most window.
IntPtr desktop = new IntPtr(0);
// The running form we are testing this code with.
IntPtr form1 = System.Windows.Forms.Application.OpenForms[0].Handle;
// So we're setting our window Z-index to that of the desktop,
// but we setting flags for showing the window and then not not moving and resizing it.
SetWindowPos(form1, desktop, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW);
The Spy++ is really a great tool to learn about the structure of windows and child windows. We found out that setting the IntPtr to Zero will automatically make it select the Desktop (most top) window.
Download spy++ http://mdb-blog.blogspot.com/2010/11/microsoft-spy-or-spyxx-for-download.html then check what's the desktop handle and the start menu handle respectively. This is just to make the proof of concept later you have to find out a better way of taking the handles. Using P\Invoke calls you can get those windows z-order
int GetZOrder(IntPtr hWnd)
{
var z = 0;
for (IntPtr h = hWnd; h != IntPtr.Zero; h = GetWindow(h, 3)) z++;
return z;
}
That code was copied from this question How to get the z-order in windows?
Then you can use SetWindowPos https://msdn.microsoft.com/en-us/library/windows/desktop/ms633545%28v=vs.85%29.aspx to position your own windows exactly where you want it to be. If you are using windows 8 have in mind that a lot of folks have ClassicShell installed on their machines. Good luck.
I am using the below code to block the taskbar which is working perfectly.
But since my application is running in background, the only way to exit the application
is by killing the .exe from task manager. So while exiting like this, the blocked task bar remains at the same state. But actually it shud resume the taskbar on exiting the application.
The reason i am doing this is, it is a kiosk application.
what is the way to overcome this.
public class Taskbar
{
[DllImport("user32.dll")]
public static extern int FindWindow(string className, string windowText);
[DllImport("user32.dll")]
public static extern int ShowWindow(int hwnd, int command);
public const int SW_HIDE = 0;
public const int SW_SHOW = 1;
public int _taskbarHandle;
protected static int Handle
{
get
{
return FindWindow("Shell_TrayWnd", "");
}
}
public Taskbar()
{
_taskbarHandle = FindWindow("Shell_TrayWnd", "");
}
public static void Show()
{
ShowWindow(Handle, SW_SHOW);
}
public static void Hide()
{
ShowWindow(Handle, SW_HIDE);
}
}
Why not just use this implementation to run completely fullscreen?
http://www.codeproject.com/KB/cs/FullScreenDotNetApp.aspx
Like the others have said when you killin the application no.
Your post is a bit sparse on why you cannot close your application gracefully, so il suggest this method.
1)
Hotkeys ( http://www.codeproject.com/KB/system/Hotkeys.aspx ) that can be pressed that will close down your application gracefully. I personaly like this method, as i use hotkeys in many of my apps.
2)
Starting a seperate application that will wake up every XXX and check if the main application is running, if its not running run the Show code and then kill itself. This method is very simular to how viruses often work, so its tried and works :)
If your only way to exit is by killing it, then I am afraid you can't reset the property back to normal.
There can be a workaround to this.
Create a service which monitors your application through polling and when it finds your application as 'not running', it restores the TaskBar to normal.
There can be other similar workarounds to this but I can't think of a way of doing this from within your application given the limitation.
For exiting the application, i am registering a hot key combination and resuming the task bar and kill the process from taskbar programatically.
you can make your application check for the existance of a file (or any other thing you can control from outside and the app have access to it), if found: dispose & exit.
it's dirty but gives a little bit more control of how your application terminate than killing it from the task manager.
I have a requirement that an application I am working on prevent the user from being able to easily capture the contents of the screen.
I have communicated that there is no feasible way to completely prevent this from happening, but I'm looking for methods to introduce some hurdles to the process.
I'm using C#/.NET 2.0 and WinForms
You can't.
The best you can do is render to a hardware accelerated device on an overlay, similar to what video players used to do. Basically, you paint your entire window blue, and render your graphics onto the video card, and internally the video card will replace the blue with the graphics. The downside to this is you have to give up using winforms controls, and I don't know of any way to do this with .NET easily. I think if you use DirectShow.NET, one of their samples is putting your own graphics into a stream.
Even after doing all of that, it's still possible to get a screenshot. Just take a picture of the screen with a digital camera.
From here:
A. Windows implements Print Screen using a registered hotkey. Windows
uses the predefined hotkeys IDHOT_SNAPDESKTOP and IDHOT_SNAPWINDOW to
handle Print Screen. These correspond to Print Screen, which captures
the entire screen, and Alt+Print Screen, which captures only the
active window. To disable these functions all you have to do is
register the hotkeys, which causes Windows to send your app a
WM_HOTKEY message when the user presses either hotkey. Your
implementation can ignore the message to bypass the default
screen-capture behavior. A good place to do it is in your mainframe
class.
FWIW, it is possible. Here's some code:
This would be a dll that you create, then call the HookKeyboard method from your application. I've tested it and it works. Granted, if someone takes a picture with a camera it can't help, but, point made. NYAH!
namespace KeyboardHook
{
public class Hooker
{
[StructLayout(LayoutKind.Sequential)]
public struct KBDLLHOOKSTRUCT
{
public int vkCode;
public int scanCode;
public int flags;
public int time
;
public int extraInfo;
}
public delegate int HookProc(int nCode, int wParam, IntPtr ptrKBDLLHOOKSTRUCT);
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
public static extern IntPtr SetWindowsHookEx(int idHook, HookProc callBack, IntPtr hMod, int threadId);
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
public static extern int CallNextHookEx(IntPtr hhk, int nCode, int wParam, IntPtr lParam);
private static IntPtr kbh_Handle;
private static HookProc kbh_HookProc;
private const int VK_SNAPSHOT = 0x2C;
private const int WM_KEYDOWN = 0x0100;
private const int WM_SYSKEYDOWN = 0x0104;
private const int WH_KEYBOARD_LL = 13;
private static int LowLevelKeyboardProc(int nCode, int wParam, IntPtr lParam)
{
if (nCode < 0)
{
CallNextHookEx(kbh_Handle, nCode, wParam, lParam);
return 0;
}
if (wParam == WM_KEYDOWN)
{
IntPtr kbdll = lParam;
KBDLLHOOKSTRUCT kbdllstruct = (KBDLLHOOKSTRUCT)Marshal.PtrToStructure(kbdll, typeof(KBDLLHOOKSTRUCT));
if (kbdllstruct.vkCode == VK_SNAPSHOT)
return -1;
}
return CallNextHookEx(kbh_Handle, nCode, wParam, lParam);
}
public static void HookKeyboard()
{
try
{
kbh_HookProc = LowLevelKeyboardProc;
kbh_Handle = SetWindowsHookEx(WH_KEYBOARD_LL, kbh_HookProc, Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly().GetModules()[0]), 0);
if (kbh_Handle != IntPtr.Zero)
System.Diagnostics.Debug.WriteLine(String.Format("It worked! HookHandle: {0}", kbh_Handle));
else
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(String.Format("ERROR: {0}", ex.Message));
}
}
}
}
You can try using IpcProtectWindow provided in msipc.dll.
[DllImport("msipc.dll", SetLastError = false, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
internal static extern int IpcProtectWindow([In] IntPtr hwnd);
Download the SDK from Microsoft
Call the function above and provide the handle of the form you would like to protect. (Form.Handle property)
You'll have two cases here that you need to worry about. One, when your window/application has focus, the other when it doesn't have focus.
When it doesn't have focus, there's not a whole lot you can do, i.e. if the user clicks off of your app and onto the desktop, keys aren't sent to your app so you'll never see them. In that case, you can minimize to the tray when your app loses focus (or, perhaps, place a "blank" panel over the form to prevent users from seeing anything on it which will also prevent a print-screen from being useful).
In the other case, when you have focus, capture keystrokes and examine them. If the Alt key is down and the PrintScreen key is down, reset the value so that a print-screen doesn't occur. (Come to think of it, that may not work. I'd need to test it to be sure.)
You could look into what movie players do. I believe they render directly to a hardware surface (via DirectX). I suspect that you'd need to do this.
This doesn't really answer the questions, but keep in mind that there exists tools to capture screen, and that a simple camera breaks everything.
I mean ok you "have to", but I would (but I'm young and still student, so I don't know much about what can be said) answer that this is just stupid.
Check out the new tech - sivizion.com, they prevent print screen all together - no way to bypass it. If anyone will figure out a way how to hack it, please post here, I couldn't. I think they also license their tech, not sure, check it out.
Well, you could try capturing the button, but I'm not sure how well that will work.
One thing that always annoyed me was that whenever I played a movie, it would never take screenshots of it. If you can render through a separate context, it would make it really annoying to take a picture of it. Perhaps you can send your screen output through something like that?
There are applications that can capture the screen from OpenGL and DirectX apps ! (depending (they are used for recording game movies)
ps. windows aero is DirectX
http://www.fraps.com/
i think thats the application
You can make any casual Print Screen useless using Visual Cryptography and taking advantage of retinal persistence (see this article for details, and bit.ly/vcrypto for a web demo).
The idea is to alternate at high frequency between two or more random noise images, that will combine through persistence of vision to reveal the content. A screen capture will only grab one image, with meaningless random noise.
This comes at the cost of flickering and inducing user headaches, can be defeated by a camera taking a picture of the screen, or by a less casual user that knows photoshop, but will defeat any kind of casual screen capture or frame grabbing.
Might occasionally be useful, in an academic meaning of the term!
It is too late but there is a quick work around,
Simply use it in MDI form
Set TopMost Property of form True, then write below event
private void frmMDI_Deactivate(object sender, EventArgs e){Clipboard.Clear();}
after taking print screen user have to minimize the application, the moment user minimize the app, we are clearing clipboard.
you can use this in logout function or when screen move or resize or any other form event as required :)
Snipping tool also can't copy screens by this if TopMost Property is true.
Yes we can't stop user from capturing screen from external device like phone or cam.
In windows form application, Use this code in form keyup event,
if (e.KeyCode == Keys.PrintScreen)
{
Clipboard.Clear();
}
Form keypreview should be TRUE
Microsoft has been developed an API named SetWindowDisplayAffinity to support the window content protection. This feature enables applications to protect application content from being captured or copied through a specific set of public operating system features and APIs
SetWindowDisplayAffinity(hWnd, WDA_MONITOR);
I solved it using a Timer object and Clipboard.Clear() method.
First add a Timer to your main form with Interval=1 (Very fast), then add the following code in its event:
Clipboard.Clear();