OpenGL Wrapper in C# - c#

I wrote a simple class to create a window and initialize OpenGL to that window. It works fine in native c++ and in CLI as well. But as soon as I import the CLI class as DLL into my C# project the rendering fails. A blank window shows up but the rendering doesn't work. The SwapBuffers and the GL rendering get called but nothing happens. Do you have any idea what can be wrong?
(Sorry I am not a native speaker)
OpenGLClass.cpp
#include "OpenGLClass.h"
#include <iostream>
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam);
OpenGLClass::OpenGLClass()
{
}
OpenGLClass::~OpenGLClass()
{
}
bool OpenGLClass::Initialize()
{
if (InitWindow())
return InitOGL();
else
return false;
}
void OpenGLClass::Run()
{
MSG msg = { 0 };
while (true)
{
if (PeekMessage(&msg, NULL, NULL, NULL, PM_REMOVE))
{
if (msg.message == WM_QUIT)
break;
TranslateMessage(&msg);
DispatchMessage(&msg);
}
else
{
Render();
SwapBuffers(m_hDevContext);
}
}
}
void OpenGLClass::Render()
{
glViewport(0, 0, 800, 600);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0, (float)800 / (float)600, 1, 1000);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(0, 0, 10,
0, 0, 0,
0, 1, 0);
glClearColor(0.2, 0.5, 0.8, 1.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
static float i = 0.01f;
i += 0.001f;
float c = cos(i);
float s = sin(i);
glBegin(GL_TRIANGLES);
glColor3f(c, 0, 0); // red
glVertex3f(1 + c, 0 + s, 0);
glColor3f(c, s, 0); // yellow
glVertex3f(0 + c, 1 + s, 0);
glColor3f(s, 0.1f, s); // magenta
glVertex3f(-1 + c, 0 + s, 0);
glEnd();
}
bool OpenGLClass::InitWindow()
{
WNDCLASSEX wc;
m_hInstance = GetModuleHandle(NULL);
wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
wc.lpfnWndProc = WndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = m_hInstance;
wc.hIcon = LoadIcon(NULL, IDI_WINLOGO);
wc.hIconSm = wc.hIcon;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
wc.lpszMenuName = NULL;
wc.lpszClassName = "OpenGLWindow";
wc.cbSize = sizeof(WNDCLASSEX);
if (!RegisterClassEx(&wc))
{
MessageBox(NULL, "RegisterClassEx() failed", "Error", MB_OK);
return false;
}
int screenWidth = GetSystemMetrics(SM_CXSCREEN);
int screenHeight = GetSystemMetrics(SM_CYSCREEN);
screenWidth = 800;
screenHeight = 600;
int nStyle = WS_POPUP;
m_hwnd = CreateWindowEx(WS_EX_APPWINDOW, "OpenGLWindow", "WindowTitle", nStyle, 0, 0, screenWidth, screenHeight, NULL, NULL, m_hInstance, NULL);
ShowWindow(m_hwnd, SW_SHOW);
return true;
}
bool OpenGLClass::InitOGL()
{
m_hDevContext = GetDC(m_hwnd);
PIXELFORMATDESCRIPTOR pfd = { 0 };
pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR);
pfd.nVersion = 1;
pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
pfd.iPixelType = PFD_TYPE_RGBA;
pfd.cColorBits = 32;
pfd.cDepthBits = 24;
pfd.cStencilBits = 24;
int format = ChoosePixelFormat(m_hDevContext, &pfd);
if (format == 0)
return false;
std::cout << "Pixel Format: " << format << std::endl;
if (!SetPixelFormat(m_hDevContext, format, &pfd))
return false;
m_GLRenderContext = wglCreateContext(m_hDevContext);
if (!wglMakeCurrent(m_hDevContext, m_GLRenderContext))
return false;
GLint GlewInitResult = glewInit();
if (GLEW_OK != GlewInitResult)
{
return false;
}
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
return true;
}
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
PAINTSTRUCT ps;
HDC hdc;
switch (message)
{
case WM_KEYDOWN:
if (wParam == VK_ESCAPE)
{
PostQuitMessage(0);
DestroyWindow(hwnd);
}
break;
case WM_CLOSE:
PostQuitMessage(0);
DestroyWindow(hwnd);
break;
default:
return DefWindowProc(hwnd, message, wParam, lParam);
}
return 0;
}
WrapperClass.h
#pragma once
#include <OpenGLClass.h>
public ref class WrapperClass
{
public:
WrapperClass() : m_Impl(new OpenGLClass) {}
~WrapperClass() {
delete m_Impl;
}
protected:
!WrapperClass() {
delete m_Impl;
}
public:
inline bool Initialize()
{
return m_Impl->Initialize();
}
inline void Run()
{
m_Impl->Run();
}
private:
OpenGLClass* m_Impl;
};
The C# code
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
BackgroundWorker bw = new BackgroundWorker();
WrapperClass wc;
public Form1()
{
InitializeComponent();
InitOGL();
}
private void InitOGL()
{
wc = new WrapperClass();
if(wc.Initialize())
{
bw.DoWork += Bw_DoWork;
bw.RunWorkerAsync();
}
}
private void Bw_DoWork(object sender, DoWorkEventArgs e)
{
wc.Run();
}
}
}

As BDL and starmole pointed out, I was running the InitOGL and the Render on different thread.

Related

C# Camera Capture with AviCap32.dll

I'm trying to capture images from my webcam by using avicap32.dll. An event should be called when a new image is available. The problem is that it only shows a black image with a few rows of colored pixels at the bottom (Sample image).
I DON'T want to use any other libraries like Aforge, DirectShow, OpenCV or something similar.
Here is my code:
public class CameraCapture2
{
[DllImport("user32", EntryPoint = "SendMessage")]
static extern bool SendMessage(int hWnd, uint wMsg, int wParam, int lParam);
[DllImport("user32", EntryPoint = "SendMessage")]
static extern int SendBitmapMessage(int hWnd, uint wMsg, int wParam, ref BITMAPINFO lParam);
[DllImport("user32", EntryPoint = "SendMessage")]
static extern int SendHeaderMessage(int hWnd, uint wMsg, int wParam, CallBackDelegate lParam);
[DllImport("avicap32.dll", EntryPoint = "capCreateCaptureWindow")]
static extern int capCreateCaptureWindow(string lpszWindowName, int dwStyle, int X, int Y, int nWidth, int nHeight, int hwndParent, int nID);
delegate void CallBackDelegate(IntPtr hwnd, ref VIDEOHEADER hdr);
CallBackDelegate delegateFrameCallBack;
AutoResetEvent autoEvent = new AutoResetEvent(false);
Thread frameThread;
public event EventHandler<NewFrameEventArgs> NewFrame;
public int FPS = 0;
public const int BitsPerPixel = 24; //RGB (by changing this value, change the other PixelFormats)
public int frameWidth = 0;
public int frameHeight = 0;
public int camID = 0;
int camHwnd, parentHwnd;
bool bStart = false;
object threadLock = new object();
int preferredFPSms;
public CameraCapture2(int frameWidth, int frameHeight, int preferredFPS, int camID, int parentHwnd)
{
this.frameWidth = frameWidth;
this.frameHeight = frameHeight;
this.parentHwnd = parentHwnd;
this.camID = camID;
PreferredFPS = preferredFPS;
delegateFrameCallBack = FrameCallBack;
}
public void Start()
{
try
{
camHwnd = capCreateCaptureWindow("WebCam", 0, 0, 0, frameWidth, frameHeight, parentHwnd, camID);
// connect to the device
if (SendMessage(camHwnd, WM_CAP.WM_CAP_DRIVER_CONNECT, 0, 0))
{
BITMAPINFO bInfo = new BITMAPINFO();
bInfo.bmiHeader = new BITMAPINFOHEADER();
bInfo.bmiHeader.biSize = (uint)Marshal.SizeOf(bInfo.bmiHeader);
bInfo.bmiHeader.biWidth = frameWidth;
bInfo.bmiHeader.biHeight = frameHeight;
bInfo.bmiHeader.biPlanes = 1;
bInfo.bmiHeader.biBitCount = BitsPerPixel; // bits per pixel, 24 - RGB
//Enable preview mode. In preview mode, frames are transferred from the
//capture hardware to system memory and then displayed in the capture
//window using GDI functions.
SendMessage(camHwnd, WM_CAP.WM_CAP_SET_PREVIEW, 1, 0);
SendMessage(camHwnd, WM_CAP.WM_CAP_SET_PREVIEWRATE, 34, 0); // sets the frame display rate in preview mode
SendBitmapMessage(camHwnd, WM_CAP.WM_CAP_SET_VIDEOFORMAT, Marshal.SizeOf(bInfo), ref bInfo);
frameThread = new Thread(new ThreadStart(this.FrameGrabber));
bStart = true; // First, set variable
frameThread.Priority = ThreadPriority.Lowest;
frameThread.Start(); // Only then put thread to the queue
}
else
throw new Exception("Cannot connect to device");
}
catch (Exception e)
{
Stop();
throw new Exception("Error: " + e.Message);
}
}
public void Stop()
{
try
{
bStart = false;
Set();
SendMessage(camHwnd, WM_CAP.WM_CAP_DRIVER_DISCONNECT, 0, 0);
}
catch { }
}
private void FrameGrabber()
{
while (bStart) // if worker active thread is still required
{
try
{
// get the next frame. This is the SLOWEST part of the program
SendMessage(camHwnd, WM_CAP.WM_CAP_GRAB_FRAME_NOSTOP, 0, 0);
SendHeaderMessage(camHwnd, WM_CAP.WM_CAP_SET_CALLBACK_FRAME, 0, delegateFrameCallBack);
}
catch (Exception excep)
{
this.Stop(); // stop the process
throw new Exception("Capturing error:\r\n" + excep.Message);
}
}
}
/// <summary>
/// Allow waiting worker (FrameGrabber) thread to proceed
/// </summary>
public void Set()
{
autoEvent.Set();
}
private void FrameCallBack(IntPtr hwnd, ref VIDEOHEADER hdr)
{
if (NewFrame != null)
{
//Bitmap bmp = new Bitmap(frameWidth, frameHeight, frameWidth * 3, System.Drawing.Imaging.PixelFormat.Format24bppRgb, hdr.lpData);
byte[] _imageTemp = new byte[hdr.dwBufferLength];
Marshal.Copy(hdr.lpData, _imageTemp, 0, (int)hdr.dwBufferLength);
Bitmap bmp = new Bitmap(new System.IO.MemoryStream(WriteBitmapFile(frameWidth, frameHeight, _imageTemp)));
NewFrame(this, new NewFrameEventArgs(bmp));
}
// block thread for preferred milleseconds
if (preferredFPSms == 0)
autoEvent.WaitOne();
else
autoEvent.WaitOne(preferredFPSms, false);
}
private static byte[] WriteBitmapFile(int width, int height, byte[] imageData)
{
using (var stream = new System.IO.MemoryStream(imageData))
using (var bmp = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format24bppRgb))
{
System.Drawing.Imaging.BitmapData bmpData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height)
, System.Drawing.Imaging.ImageLockMode.WriteOnly
, bmp.PixelFormat
);
Marshal.Copy(imageData, 0, bmpData.Scan0, imageData.Length);
bmp.UnlockBits(bmpData);
if (bmp == null)
return null;
bmp.RotateFlip(RotateFlipType.Rotate180FlipNone);
using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
{
bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png); // get bitmap bytes
return ms.ToArray();
} // End Using stream
}
}
public void ShowVideoDialog()
{
SendMessage(camHwnd, WM_CAP.WM_CAP_DLG_VIDEODISPLAY, 0, 0);
}
public int PreferredFPS
{
get { return 1000 / preferredFPSms; }
set
{
if (value == 0)
preferredFPSms = 0;
else if (value > 0 && value <= 30)
{
preferredFPSms = 1000 / value;
}
}
}
}
public class NewFrameEventArgs
{
public Bitmap Frame;
public NewFrameEventArgs(Bitmap frame)
{
Frame = frame;
}
}
Most of this code is from Codeproject

Support Windows 11 Snap Layout in WPF app

I want to enable SnapLayout for WPF, because I use Customized Window, according to the documentation, I have to do it myself.
For Win32 apps, make sure you are responding appropriately to
WM_NCHITTEST (with a return value of HTMAXBUTTON for
the maximize/restore button).
I used the following code
private const int HTMAXBUTTON = 9;
private IntPtr HwndSourceHook(IntPtr hwnd, int msg, IntPtr wparam,
IntPtr lparam, ref bool handled)
{
switch (msg)
{
case InteropValues.WM_NCHITTEST:
try
{
int x = lparam.ToInt32() & 0xffff;
int y = lparam.ToInt32() >> 16;
var rect = new Rect(_ButtonMax.PointToScreen(
new Point()),
new Size(_ButtonMax.Width, _ButtonMax.Height));
if (rect.Contains(new Point(x, y)))
{
handled = true;
}
return new IntPtr(HTMAXBUTTON);
}
catch (OverflowException)
{
handled = true;
}
break;
}
return IntPtr.Zero;
}
SnapLayout is displayed well But the maximize button does not work and if I click on it, a button will be created next to it. How can I solve this problem?
Update:
This is complete code and works fine (without any issues (mouse hover, click,...))
private const double DPI_SCALE = 1.5;
private const int HTMAXBUTTON = 9;
private IntPtr HwndSourceHook(IntPtr hwnd, int msg, IntPtr wparam, IntPtr lparam, ref bool handled)
{
switch (msg)
{
case 0x0084:
try
{
int x = lparam.ToInt32() & 0xffff;
int y = lparam.ToInt32() >> 16;
Button _button;
if (WindowState == WindowState.Maximized)
{
_button = _ButtonRestore;
}
else
{
_button = _ButtonMax;
}
var rect = new Rect(_button.PointToScreen(
new Point()),
new Size(_button.Width * DPI_SCALE, _button.Height * DPI_SCALE));
if (rect.Contains(new Point(x, y)))
{
handled = true;
_button.Background = OtherButtonHoverBackground;
}
else
{
_button.Background = OtherButtonBackground;
}
return new IntPtr(HTMAXBUTTON);
}
catch (OverflowException)
{
handled = true;
}
break;
case 0x00A1:
int x = lparam.ToInt32() & 0xffff;
int y = lparam.ToInt32() >> 16;
Button _button;
if (WindowState == WindowState.Maximized)
{
_button = _ButtonRestore;
}
else
{
_button = _ButtonMax;
}
var rect = new Rect(_button.PointToScreen(
new Point()),
new Size(_button.Width * DPI_SCALE, _button.Height * DPI_SCALE));
if (rect.Contains(new Point(x, y)))
{
handled = true;
IInvokeProvider invokeProv = new ButtonAutomationPeer(_button).GetPattern(PatternInterface.Invoke) as IInvokeProvider;
invokeProv?.Invoke();
}
break;
default:
handled = false;
break;
}
return IntPtr.Zero;
}
you need to define OtherButtonHoverBackground and OtherButtonBackground or replace with SolidColorBrush.

How to get the windows messages according to the child?

I am creating a form inside another form. In the child form I have created taskbar button. I am overriding WndProc in the button.I am referring https://www.codeproject.com/Articles/10171/Adding-a-Minimize-to-tray-button-to-a-Form-s-caption bar. But whenever I am getting messages(mouse coordinates) , it is given with respect to the parent form. This makes trouble in calculations .I want those with respect to child form.How to achieve this?
This is the code for form1
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Form2 form2 = new Form2();
form2.TopLevel = false;
form2.AutoScroll = true;
form2.Anchor = AnchorStyles.Top;
form2.Dock = DockStyle.Fill;
this.splitContainer1.Panel2.Controls.Add(form2);
form2.Show();
}
}
this is form2.
public partial class Form2 : Form
{
TyronM.MinTrayBtn Pin_Button;
public Form2()
{
InitializeComponent();
Pin_Button = new TyronM.MinTrayBtn(this);
Pin_Button.MinTrayBtnClicked += new TyronM.MinTrayBtnClickedEventHandler(this.Pin_Button_Clicked);
}
public void Pin_Button_Clicked(object sender, EventArgs e)
{
MessageBox.Show("Pin button got Clicked");
}
protected override void WndProc(ref Message message)
{
const int WM_SYSCOMMAND = 0x0112;
const int SC_MOVE = 0xF010;
switch (message.Msg)
{
case WM_SYSCOMMAND:
int command = message.WParam.ToInt32() & 0xfff0;
if (command == SC_MOVE)
return;
break;
}
base.WndProc(ref message);
}
}
And this is for button.
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Diagnostics;
using System.Resources;
using System.Runtime.InteropServices;
namespace TyronM {
public delegate void MinTrayBtnClickedEventHandler(object sender, EventArgs e);
/// <summary>
/// Summary description for Class.
/// </summary>
public class MinTrayBtn : NativeWindow {
bool pinned = false;
bool pressed = false;
Size wnd_size = new Size();
public bool captured;
Form parent;
public event MinTrayBtnClickedEventHandler MinTrayBtnClicked;
#region Constants
const int WM_SIZE = 5;
const int WM_SYNCPAINT = 136;
const int WM_MOVE = 3;
const int WM_ACTIVATE = 6;
const int WM_LBUTTONDOWN =513;
const int WM_LBUTTONUP =514;
const int WM_LBUTTONDBLCLK =515;
const int WM_MOUSEMOVE = 512;
const int WM_PAINT = 15;
const int WM_GETTEXT = 13;
const int WM_NCCREATE =129;
const int WM_NCLBUTTONDOWN = 161;
const int WM_NCLBUTTONUP = 162;
const int WM_NCMOUSEMOVE = 160;
const int WM_NCACTIVATE =134;
const int WM_NCPAINT = 133;
const int WM_NCHITTEST = 132;
const int WM_NCLBUTTONDBLCLK = 163;
const int VK_LBUTTON = 1;
const int SM_CXSIZE = 30;
const int SM_CYSIZE = 31;
#endregion
#region Extra Constants
const int WM_MBUTTONUP = 0x0208;
#endregion
#region WinAPI Imports
[DllImport("user32")]
public static extern int GetWindowDC(int hwnd);
[DllImport("user32")]
public static extern short GetAsyncKeyState(int vKey);
[DllImport("user32")]
public static extern int SetCapture(int hwnd);
[DllImport("user32")]
public static extern bool ReleaseCapture();
[DllImport("user32")]
public static extern int GetSysColor(int nIndex);
[DllImport("user32")]
public static extern int GetSystemMetrics(int nIndex);
#endregion
#region Constructor and Handle-Handler ^^
public MinTrayBtn(Form parent) {
parent.HandleCreated += new EventHandler(this.OnHandleCreated);
parent.HandleDestroyed+= new EventHandler(this.OnHandleDestroyed);
parent.TextChanged+= new EventHandler(this.OnTextChanged);
this.parent = parent;
}
// Listen for the control's window creation and then hook into it.
internal void OnHandleCreated(object sender, EventArgs e){
// Window is now created, assign handle to NativeWindow.
AssignHandle(((Form)sender).Handle);
}
internal void OnHandleDestroyed(object sender, EventArgs e) {
// Window was destroyed, release hook.
ReleaseHandle();
}
// Changing the Text invalidates the Window, so we got to Draw the Button again
private void OnTextChanged(object sender, EventArgs e) {
DrawButton();
}
#endregion
#region WndProc
[System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name="FullTrust")]
protected override void WndProc(ref Message m){
//label3.Text = "Button pressed: " + pressed;
//label4.Text = "Mouse captured: " + captured;
// Change the Pressed-State of the Button when the User pressed the
// left mouse button and moves the cursor over the button
if (m.Msg == WM_LBUTTONDBLCLK ||m.Msg == WM_LBUTTONDOWN || m.Msg == WM_LBUTTONUP
||m.Msg == WM_MBUTTONUP
)
MessageBox.Show("click happened");
if(m.Msg==WM_MOUSEMOVE) {
Point pnt2 = new Point((int)m.LParam);
Size rel_pos2 = new Size(parent.PointToClient(new Point(parent.Location.X, parent.Location.Y)));
// Not needed because SetCapture seems to convert the cordinates anyway
//pnt2 = PointToClient(pnt2);
pnt2-=rel_pos2;
//label2.Text = "Cursor #"+pnt2.X+"/"+pnt2.Y;
if(pressed) {
Point pnt = new Point((int)m.LParam);
Size rel_pos = new Size(parent.PointToClient(new Point(parent.Location.X, parent.Location.Y)));
//pnt = PointToClient(pnt);
pnt-=rel_pos;
if(!MouseinBtn(pnt)) {
pressed = false;
DrawButton();
}
} else {
if((GetAsyncKeyState(VK_LBUTTON)&(-32768))!=0) {
Point pnt = new Point((int)m.LParam);
Size rel_pos = new Size(parent.PointToClient(new Point(parent.Location.X, parent.Location.Y)));
//pnt = PointToClient(pnt);
pnt-=rel_pos;
if(MouseinBtn(pnt)) {
pressed = true;
DrawButton();
}
}
}
}
// Ignore Double-Clicks on the Traybutton
if(m.Msg==WM_NCLBUTTONDBLCLK) {
Point pnt = new Point((int)m.LParam);
Size rel_pos = new Size(parent.PointToClient(new Point(parent.Location.X, parent.Location.Y)));
pnt = parent.PointToClient(pnt);
pnt-=rel_pos;
if(MouseinBtn(pnt)) {
return;
}
}
#region NOT WORKING
// Button released and eventually clicked
if(m.Msg==WM_LBUTTONUP)
{
ReleaseCapture();
captured = false;
if(pressed) {
pressed = false;
DrawButton();
Point pnt = new Point((int)m.LParam);
Size rel_pos = new Size(parent.PointToClient(new Point(parent.Location.X, parent.Location.Y)));
pnt-=rel_pos;
if(MouseinBtn(pnt)) {
//TrayButton_clicked();
EventArgs e = new EventArgs();
if (MinTrayBtnClicked != null)
MinTrayBtnClicked(this, e);
return;
}
}
}
#endregion
// Clicking the Button - Capture the Mouse and await until the Uses relases the Button again
if(m.Msg==WM_NCLBUTTONDOWN) {
//MessageBox.Show("clicked");
Point pnt = new Point((int)m.LParam);
Size rel_pos = new Size(parent.PointToClient(new Point(parent.Location.X, parent.Location.Y)));
pnt = parent.PointToClient(pnt);
pnt-=rel_pos;
if(MouseinBtn(pnt)) {
MessageBox.Show("clicked");
pressed = true;
DrawButton();
SetCapture((int)parent.Handle);
captured = true;
return;
}
}
// Drawing the Button and getting the Real Size of the Window
if(m.Msg == WM_ACTIVATE || m.Msg==WM_SIZE || m.Msg==WM_SYNCPAINT || m.Msg==WM_NCACTIVATE || m.Msg==WM_NCCREATE || m.Msg==WM_NCPAINT || m.Msg==WM_NCACTIVATE || m.Msg==WM_NCHITTEST || m.Msg==WM_PAINT) {
if(m.Msg==WM_SIZE) wnd_size = new Size(new Point((int)m.LParam));
DrawButton();
}
base.WndProc(ref m);
}
#endregion
#region Button-Specific Functions
public bool MouseinBtn(Point click) {
int btn_width = GetSystemMetrics(SM_CXSIZE);
int btn_height = GetSystemMetrics(SM_CYSIZE);
Size btn_size = new Size(btn_width, btn_height);
Point pos = new Point(wnd_size.Width - 3 * btn_width - 12 - (btn_width - 18)+7, 6+4);
return click.X>=pos.X && click.X<=pos.X+btn_size.Width &&
click.Y>=pos.Y && click.Y<=pos.Y+btn_size.Height;
}
public void DrawButton() {
Graphics g = Graphics.FromHdc((IntPtr)GetWindowDC((int)parent.Handle)); //m.HWnd));
DrawButton(g, pressed);
}
public void DrawButton(Graphics g, bool pressed) {
int btn_width = GetSystemMetrics(SM_CXSIZE);
int btn_height = GetSystemMetrics(SM_CYSIZE);
//Point pos = new Point(wnd_size.Width-3*btn_width-12-(btn_width-18),6);
Point pos = new Point(wnd_size.Width - 3 * btn_width - 12 - (btn_width - 18)+7, 6+4);
// real button size
btn_width-=2;
btn_height-=4;
Color light = SystemColors.ControlLightLight;
Color icon = SystemColors.ControlText;
Color background = SystemColors.Control;
Color shadow1 = SystemColors.ControlDark;
Color shadow2 = SystemColors.ControlDarkDark;
Color tmp1, tmp2;
if(pressed) {
tmp1 = shadow2;
tmp2 = light;
} else {
tmp1 = light;
tmp2 = shadow2;
}
g.DrawLine(new Pen(tmp1),pos, new Point(pos.X+btn_width-1,pos.Y));
g.DrawLine(new Pen(tmp1),pos, new Point(pos.X,pos.Y+btn_height-1));
if(pressed) {
g.DrawLine(new Pen(shadow1),pos.X+1, pos.Y+1, pos.X+btn_width-2, pos.Y+1);
g.DrawLine(new Pen(shadow1),pos.X+1, pos.Y+1, pos.X+1, pos.Y+btn_height-2);
} else {
g.DrawLine(new Pen(shadow1),pos.X+btn_width-2, pos.Y+1, pos.X+btn_width-2, pos.Y+btn_height-2);
g.DrawLine(new Pen(shadow1),pos.X+1, pos.Y+btn_height-2, pos.X+btn_width-2, pos.Y+btn_height-2);
}
g.DrawLine(new Pen(tmp2),pos.X+btn_width-1, pos.Y+0, pos.X+btn_width-1, pos.Y+btn_height-1);
g.DrawLine(new Pen(tmp2),pos.X+0, pos.Y+btn_height-1, pos.X+btn_width-1, pos.Y+btn_height-1);
g.FillRectangle(new SolidBrush(background),pos.X+1+Convert.ToInt32(pressed), pos.Y+1+Convert.ToInt32(pressed), btn_width-3,btn_height-3);
#region Added Code
g.FillRectangle(new SolidBrush(icon),pos.X+(float)0.5625*btn_width+Convert.ToInt32(pressed),pos.Y+(float)0.6428*btn_height+Convert.ToInt32(pressed),btn_width*(float)0.1875,btn_height*(float)0.143);
g.DrawImage(Image.FromFile("red_Pushpin.jfif"),new Rectangle( pos,new Size(btn_width,btn_height)));
#endregion
}
#endregion
}
}
This is code for main
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
This is the screenshot of the winform.
EDIT:
Upon investigation I found that WM_LBUTTONUP(Mouse left button up) is not triggered. Or it is not coming inside WndProc.
EDIT1:
It seems there was a problem in brackets.I changed the if conditions into switch case. This somewhat cleared the "Mouse left button up" problem. Now it is properly triggering. The remaining problem is mouse points based on parent form.

System.Console as a log window with input line

I'm writing a console application that needs user input on the bottom line while text is scrolling. The idea is to have text scroll and leave an input line at the bottom. I want text editing functionality (arrow-keys, insert, delete, etc). I'd love to be able to have static "status lines" too (lines unaffected by scrolling).
A real world example would be Irssi:
In my code I'm hooking up to NLog and writing its output to screen while also providing an input line to the user. It is done by "pausing input" on write: using Console.MoveBufferArea to move text up, disabling cursor, repositioning cursor, writing log-text, repositioning cursor back to input line and enabling cursor. It almost works, but there are some problems:
It is very slow. In cases where I write 20-30 lines the application slows down considerably. (Can be solved with buffering incoming, but won't solve scroll speed.)
Lines that overflow (i.e. exception stacktrace) leaves a line at the very bottom of the screen.
Lines that overflow are (partially) overwritten as text scrolls up. This also messes up input line.
Scrolling up/down does not work.
Is there a library to help me do this?
If not then how do I fix speed? How do I fix scrolling?
Cross platform solution preferred.
public class InputConsole
{
private static readonly object _bufferLock = new object();
private static int _windowWidth = Console.BufferWidth;
private static int _windowHeight = Console.BufferHeight;
private static int _windowLeft = Console.WindowLeft;
private static int _windowTop = Console.WindowTop;
public InputConsole()
{
MethodCallTarget target = new MethodCallTarget();
target.ClassName = typeof(InputConsole).AssemblyQualifiedName;
target.MethodName = "LogMethod";
target.Parameters.Add(new MethodCallParameter("${level}"));
target.Parameters.Add(new MethodCallParameter("${message}"));
target.Parameters.Add(new MethodCallParameter("${exception:format=tostring}"));
target.Parameters.Add(new MethodCallParameter("[${logger:shortName=true}]"));
SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Trace);
try
{
Console.SetWindowSize(180, 50);
Console.SetBufferSize(180, 50);
_windowWidth = Console.BufferWidth;
_windowHeight = Console.BufferHeight;
}
catch (Exception exception)
{
Console.WriteLine("Unable to resize console: " + exception);
}
}
public void Run()
{
string input;
do
{
lock (_bufferLock)
{
Console.SetCursorPosition(0, _windowHeight - 1);
Console.Write("Command: ");
Console.CursorVisible = true;
}
Console.BackgroundColor = ConsoleColor.Black;
Console.ForegroundColor = ConsoleColor.Yellow;
input = Console.ReadLine();
lock (_bufferLock)
{
Console.CursorVisible = false;
}
} while (!string.Equals(input, "quit", StringComparison.OrdinalIgnoreCase));
}
public static void LogMethod(string level, string message, string exception, string caller)
{
if (Console.BufferHeight == _windowHeight)
Console.MoveBufferArea(_windowLeft, _windowTop + 1, Console.BufferWidth, Console.BufferHeight - 2, _windowLeft, _windowTop);
var fgColor = ConsoleColor.White;
var bgColor = ConsoleColor.Black;
switch (level.ToUpper())
{
case "TRACE":
fgColor = ConsoleColor.DarkGray;
break;
case "DEBUG":
fgColor = ConsoleColor.Gray;
break;
case "INFO":
fgColor = ConsoleColor.White;
break;
case "WARNING":
fgColor = ConsoleColor.Cyan;
break;
case "ERROR":
fgColor = ConsoleColor.White;
bgColor = ConsoleColor.Red;
break;
}
var str = string.Format("({0}) {1} {2} {3}", level.ToUpper(), caller, message, exception);
WriteAt(_windowLeft, _windowHeight - 3, str, fgColor, bgColor);
}
public static void WriteAt(int left, int top, string s, ConsoleColor foregroundColor = ConsoleColor.White, ConsoleColor backgroundColor = ConsoleColor.Black)
{
lock (_bufferLock)
{
var currentBackgroundColor = Console.BackgroundColor;
var currentForegroundColor = Console.ForegroundColor;
Console.BackgroundColor = backgroundColor;
Console.ForegroundColor = foregroundColor;
int currentLeft = Console.CursorLeft;
int currentTop = Console.CursorTop;
var currentVisible = Console.CursorVisible;
Console.CursorVisible = false;
Console.SetCursorPosition(left, top);
Console.Write(s);
Console.SetCursorPosition(currentLeft, currentTop);
Console.CursorVisible = currentVisible;
Console.BackgroundColor = currentBackgroundColor;
Console.ForegroundColor = currentForegroundColor;
}
}
}
Doing further research into text console in Windows I seems it is difficult to make it go faster. Through a custom implementation with lower redraw rates (less to WriteConsoleOutput) I was able to get just over 10x speed increase over Console.WriteLine.
However since Console.WriteLine enforces the "scroll everything when we reach bottom" I was using Console.MoveBufferArea. Tests shows that my implementation of MoveBufferArea (included in my original question) was around 90x slower than Console.WriteLine. With my new implementation using WriteConsoleOutput I was however able to get a 1356x speed increase over MoveBufferedArea.
Since it was a bit difficult to find information about it I have detailed my finding in a blog post. I'm also attaching the code to this answer for posterity.
I have written a class that allows me to scroll individual boxes. I have also implemented a line input system to emulate that of standard Console.ReadLine();. Note that this implementation is missing home/end-support (easy to fix though).
Note that to get any speed increase from it you have to set box.AutoRedraw = false; and manually call box.Draw(); regularly. With box.AutoRedraw = true; (calling Draw() on every Write()) this solution is actually 30 times slower than Console.WriteLine and 3 times faster than MoveBufferArea.
Example on how to use:
_logBox = new InputConsoleBox(0, 0, (short)Console.BufferWidth, (short)(Console.BufferHeight - 2), InputConsoleBox.Colors.LightWhite, InputConsoleBox.Colors.Black);
_statusBox = new InputConsoleBox(0, (short)(Console.BufferHeight - 3), (short)Console.BufferWidth, 1, InputConsoleBox.Colors.LightYellow, InputConsoleBox.Colors.DarkBlue);
_inputBox = new InputConsoleBox(0, (short)(Console.BufferHeight - 2), (short)Console.BufferWidth, 1, InputConsoleBox.Colors.LightYellow, InputConsoleBox.Colors.Black);
_statusBox.WriteLine("Hey there!");
_inputBox.InputPrompt = "Command: ";
// If you are okay with some slight flickering this is an easy way to set up a refresh timer
_logBox.AutoDraw = false;
_redrawTask = Task.Factory.StartNew(async () =>
{
while (true)
{
await Task.Delay(100);
if (_logBox.IsDirty)
_logBox.Draw();
}
});
// Line input box
var line = _inputBox.ReadLine(); // Blocking while waiting for <enter>
Code:
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using Microsoft.Win32.SafeHandles;
public class InputConsoleBox
{
#region Output
#region Win32 interop
private const UInt32 STD_OUTPUT_HANDLE = unchecked((UInt32)(-11));
private const UInt32 STD_ERROR_HANDLE = unchecked((UInt32)(-12));
[DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern IntPtr GetStdHandle(UInt32 type);
[DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern SafeFileHandle CreateFile(
string fileName,
[MarshalAs(UnmanagedType.U4)] uint fileAccess,
[MarshalAs(UnmanagedType.U4)] uint fileShare,
IntPtr securityAttributes,
[MarshalAs(UnmanagedType.U4)] FileMode creationDisposition,
[MarshalAs(UnmanagedType.U4)] int flags,
IntPtr template);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool WriteConsoleOutput(
SafeFileHandle hConsoleOutput,
CharInfo[] lpBuffer,
Coord dwBufferSize,
Coord dwBufferCoord,
ref SmallRect lpWriteRegion);
[StructLayout(LayoutKind.Sequential)]
private struct Coord
{
public short X;
public short Y;
public Coord(short X, short Y)
{
this.X = X;
this.Y = Y;
}
};
[StructLayout(LayoutKind.Explicit)]
private struct CharUnion
{
[FieldOffset(0)]
public char UnicodeChar;
[FieldOffset(0)]
public byte AsciiChar;
}
[StructLayout(LayoutKind.Explicit)]
private struct CharInfo
{
[FieldOffset(0)]
public CharUnion Char;
[FieldOffset(2)]
public ushort Attributes;
public CharInfo(char #char, ushort attributes)
{
this.Char = new CharUnion();
Char.UnicodeChar = #char;
Attributes = attributes;
}
}
[StructLayout(LayoutKind.Sequential)]
private struct SmallRect
{
public short Left;
public short Top;
public short Right;
public short Bottom;
}
#endregion
#region Colors Enum
private const int HighIntensity = 0x0008;
private const ushort COMMON_LVB_LEADING_BYTE = 0x0100;
private const ushort COMMON_LVB_TRAILING_BYTE = 0x0200;
private const ushort COMMON_LVB_GRID_HORIZONTAL = 0x0400;
private const ushort COMMON_LVB_GRID_LVERTICAL = 0x0800;
private const ushort COMMON_LVB_GRID_RVERTICAL = 0x1000;
private const ushort COMMON_LVB_REVERSE_VIDEO = 0x4000;
private const ushort COMMON_LVB_UNDERSCORE = 0x8000;
private const ushort COMMON_LVB_SBCSDBCS = 0x0300;
[Flags]
public enum Colors : int
{
Black = 0x0000,
DarkBlue = 0x0001,
DarkGreen = 0x0002,
DarkRed = 0x0004,
Gray = DarkBlue | DarkGreen | DarkRed,
DarkYellow = DarkRed | DarkGreen,
DarkPurple = DarkRed | DarkBlue,
DarkCyan = DarkGreen | DarkBlue,
LightBlue = DarkBlue | HighIntensity,
LightGreen = DarkGreen | HighIntensity,
LightRed = DarkRed | HighIntensity,
LightWhite = Gray | HighIntensity,
LightYellow = DarkYellow | HighIntensity,
LightPurple = DarkPurple | HighIntensity,
LightCyan = DarkCyan | HighIntensity
}
#endregion // Colors Enum
private readonly CharInfo[] _buffer;
private readonly List<CharInfo> _tmpBuffer;
private readonly short _left;
private readonly short _top;
private readonly short _width;
private readonly short _height;
private ushort _defaultColor;
private int _cursorLeft;
private int _cursorTop;
private static SafeFileHandle _safeFileHandle;
/// <summary>
/// Automatically draw to console.
/// Unset this if you want to manually control when (and what order) boxes are writen to consoles - or you want to batch some stuff.
/// You must manually call <c>Draw()</c> to write to console.
/// </summary>
public bool AutoDraw = true;
public bool IsDirty { get; private set; }
public InputConsoleBox(short left, short top, short width, short height, Colors defaultForegroundColor = Colors.Gray, Colors defaultBackgroundColor = Colors.Black)
{
if (left < 0 || top < 0 || left + width > Console.BufferWidth || top + height > Console.BufferHeight)
throw new Exception(string.Format("Attempting to create a box {0},{1}->{2},{3} that is out of buffer bounds 0,0->{4},{5}", left, top, left + width, top + height, Console.BufferWidth, Console.BufferHeight));
_left = left;
_top = top;
_width = width;
_height = height;
_buffer = new CharInfo[_width * _height];
_defaultColor = CombineColors(defaultForegroundColor, defaultBackgroundColor);
_tmpBuffer = new List<CharInfo>(_width * _height); // Assumption that we won't be writing much more than a screenful (backbufferfull) in every write operation
//SafeFileHandle h = CreateFile("CONOUT$", 0x40000000, 2, IntPtr.Zero, FileMode.Open, 0, IntPtr.Zero);
if (_safeFileHandle == null)
{
var stdOutputHandle = GetStdHandle(STD_OUTPUT_HANDLE);
_safeFileHandle = new SafeFileHandle(stdOutputHandle, false);
}
Clear();
Draw();
}
public void Clear()
{
for (int y = 0; y < _height; y++)
{
for (int x = 0; x < _width; x++)
{
var i = (y * _width) + x;
_buffer[i].Char.UnicodeChar = ' ';
_buffer[i].Attributes = _defaultColor;
}
}
IsDirty = true;
// Update screen
if (AutoDraw)
Draw();
}
public void Draw()
{
IsDirty = false;
var rect = new SmallRect() { Left = _left, Top = _top, Right = (short)(_left + _width), Bottom = (short)(_top + _height) };
bool b = WriteConsoleOutput(_safeFileHandle, _buffer,
new Coord(_width, _height),
new Coord(0, 0), ref rect);
}
private static ushort CombineColors(Colors foreColor, Colors backColor)
{
return (ushort)((int)foreColor + (((int)backColor) << 4));
}
public void SetCursorPosition(int left, int top)
{
if (left >= _width || top >= _height)
throw new Exception(string.Format("Position out of bounds attempting to set cursor at box pos {0},{1} when box size is only {2},{3}.", left, top, _width, _height));
_cursorLeft = left;
_cursorTop = top;
}
public void SetCursorBlink(int left, int top, bool state)
{
Console.SetCursorPosition(left, top);
Console.CursorVisible = state;
//// Does not work
//var i = (top * _width) + left;
//if (state)
// _buffer[i].Attributes = (ushort)((int)_buffer[i].Attributes & ~(int)COMMON_LVB_UNDERSCORE);
//else
// _buffer[i].Attributes = (ushort)((int)_buffer[i].Attributes | (int)COMMON_LVB_UNDERSCORE);
//if (AutoDraw)
// Draw();
}
public void WriteLine(string line, Colors fgColor, Colors bgColor)
{
var c = _defaultColor;
_defaultColor = CombineColors(fgColor, bgColor);
WriteLine(line);
_defaultColor = c;
}
public void WriteLine(string line)
{
Write(line + "\n");
}
public void Write(string text)
{
Write(text.ToCharArray());
}
public void Write(char[] text)
{
IsDirty = true;
_tmpBuffer.Clear();
bool newLine = false;
// Old-school! Could definitively have been done more easily with regex. :)
var col = 0;
var row = -1;
for (int i = 0; i < text.Length; i++)
{
// Detect newline
if (text[i] == '\n')
newLine = true;
if (text[i] == '\r')
{
newLine = true;
// Skip following \n
if (i + 1 < text.Length && text[i] == '\n')
i++;
}
// Keep track of column and row
col++;
if (col == _width)
{
col = 0;
row++;
if (newLine) // Last character was newline? Skip filling the whole next line with empty
{
newLine = false;
continue;
}
}
// If we are newlining we need to fill the remaining with blanks
if (newLine)
{
newLine = false;
for (int i2 = col; i2 <= _width; i2++)
{
_tmpBuffer.Add(new CharInfo(' ', _defaultColor));
}
col = 0;
row++;
continue;
}
if (i >= text.Length)
break;
// Add character
_tmpBuffer.Add(new CharInfo(text[i], _defaultColor));
}
var cursorI = (_cursorTop * _width) + _cursorLeft;
// Get our end position
var end = cursorI + _tmpBuffer.Count;
// If we are overflowing (scrolling) then we need to complete our last line with spaces (align buffer with line ending)
if (end > _buffer.Length && col != 0)
{
for (int i = col; i <= _width; i++)
{
_tmpBuffer.Add(new CharInfo(' ', _defaultColor));
}
col = 0;
row++;
}
// Chop start of buffer to fit into destination buffer
if (_tmpBuffer.Count > _buffer.Length)
_tmpBuffer.RemoveRange(0, _tmpBuffer.Count - _buffer.Length);
// Convert to array so we can batch copy
var tmpArray = _tmpBuffer.ToArray();
// Are we going to write outside of buffer?
end = cursorI + _tmpBuffer.Count;
var scrollUp = 0;
if (end > _buffer.Length)
{
scrollUp = end - _buffer.Length;
}
// Scroll up
if (scrollUp > 0)
{
Array.Copy(_buffer, scrollUp, _buffer, 0, _buffer.Length - scrollUp);
cursorI -= scrollUp;
}
var lastPos = Math.Min(_buffer.Length, cursorI + tmpArray.Length);
var firstPos = lastPos - tmpArray.Length;
// Copy new data in
Array.Copy(tmpArray, 0, _buffer, firstPos, tmpArray.Length);
// Set new cursor position
_cursorLeft = col;
_cursorTop = Math.Min(_height, _cursorTop + row + 1);
// Write to main buffer
if (AutoDraw)
Draw();
}
#endregion
#region Input
private string _currentInputBuffer = "";
private string _inputPrompt;
private int _inputCursorPos = 0;
private int _inputFrameStart = 0;
// Not used because COMMON_LVB_UNDERSCORE doesn't work
//private bool _inputCursorState = false;
//private int _inputCursorStateChange = 0;
private int _cursorBlinkLeft = 0;
private int _cursorBlinkTop = 0;
public string InputPrompt
{
get { return _inputPrompt; }
set
{
_inputPrompt = value;
ResetInput();
}
}
private void ResetInput()
{
SetCursorPosition(0, 0);
_inputCursorPos = Math.Min(_currentInputBuffer.Length, _inputCursorPos);
var inputPrompt = InputPrompt + "[" + _currentInputBuffer.Length + "] ";
// What is the max length we can write?
var maxLen = _width - inputPrompt.Length;
if (maxLen < 0)
return;
if (_inputCursorPos > _inputFrameStart + maxLen)
_inputFrameStart = _inputCursorPos - maxLen;
if (_inputCursorPos < _inputFrameStart)
_inputFrameStart = _inputCursorPos;
_cursorBlinkLeft = inputPrompt.Length + _inputCursorPos - _inputFrameStart;
//if (_currentInputBuffer.Length - _inputFrameStart < maxLen)
// _inputFrameStart--;
// Write and pad the end
var str = inputPrompt + _currentInputBuffer.Substring(_inputFrameStart, Math.Min(_currentInputBuffer.Length - _inputFrameStart, maxLen));
var spaceLen = _width - str.Length;
Write(str + (spaceLen > 0 ? new String(' ', spaceLen) : ""));
UpdateCursorBlink(true);
}
private void UpdateCursorBlink(bool force)
{
// Since COMMON_LVB_UNDERSCORE doesn't work we won't be controlling blink
//// Blink the cursor
//if (Environment.TickCount > _inputCursorStateChange)
//{
// _inputCursorStateChange = Environment.TickCount + 250;
// _inputCursorState = !_inputCursorState;
// force = true;
//}
//if (force)
// SetCursorBlink(_cursorBlinkLeft, _cursorBlinkTop, _inputCursorState);
SetCursorBlink(_left + _cursorBlinkLeft, _top + _cursorBlinkTop, true);
}
public string ReadLine()
{
Console.CursorVisible = false;
Clear();
ResetInput();
while (true)
{
Thread.Sleep(50);
while (Console.KeyAvailable)
{
var key = Console.ReadKey(true);
switch (key.Key)
{
case ConsoleKey.Enter:
{
var ret = _currentInputBuffer;
_inputCursorPos = 0;
_currentInputBuffer = "";
return ret;
break;
}
case ConsoleKey.LeftArrow:
{
_inputCursorPos = Math.Max(0, _inputCursorPos - 1);
break;
}
case ConsoleKey.RightArrow:
{
_inputCursorPos = Math.Min(_currentInputBuffer.Length, _inputCursorPos + 1);
break;
}
case ConsoleKey.Backspace:
{
if (_inputCursorPos > 0)
{
_inputCursorPos--;
_currentInputBuffer = _currentInputBuffer.Remove(_inputCursorPos, 1);
}
break;
}
case ConsoleKey.Delete:
{
if (_inputCursorPos < _currentInputBuffer.Length - 1)
_currentInputBuffer = _currentInputBuffer.Remove(_inputCursorPos, 1);
break;
}
default:
{
var pos = _inputCursorPos;
//if (_inputCursorPos == _currentInputBuffer.Length)
_inputCursorPos++;
_currentInputBuffer = _currentInputBuffer.Insert(pos, key.KeyChar.ToString());
break;
}
}
ResetInput();
}
// COMMON_LVB_UNDERSCORE doesn't work so we use Consoles default cursor
//UpdateCursorBlink(false);
}
}
#endregion
}

AppBar Multi-Monitor

I've made a simple appBar with just a label on the top of the screen that shrinks the desktop but I'm having trouble making it appear my second monitor. I've been searching around but everything I've found has been for WPF. These are most likely the areas where I've made a mistake but if there is any other code you need to see, just let me know.
private void InitializeComponent()
{
this.ClientSize = new System.Drawing.Size(SystemInformation.WorkingArea.Width, -1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
this.Name = "MainForm";
this.Text = "AppBar";
this.Closing += new System.ComponentModel.CancelEventHandler(this.OnClosing);
this.Load += new System.EventHandler(this.OnLoad);
this.BackColor = Color.Green;
this.Padding = new Padding(0, 0, 0, 0);
Label label1 = new Label();
label1.Text = "TEXT";
label1.Width = 270;
label1.Margin = new Padding(0,0,0,0);
label1.Padding = new Padding(0,0,0,0);
label1.TextAlign = ContentAlignment.MiddleCenter;
label1.ForeColor = Color.White;
label1.Font = new Font(FontFamily.GenericSansSerif, 12,FontStyle.Regular);
label1.Location = new Point((SystemInformation.WorkingArea.Width - 270) / 2, 0);
this.Controls.Add(label1);
}
private void ABSetPos()
{
APPBARDATA abd = new APPBARDATA();
abd.cbSize = Marshal.SizeOf(abd);
abd.hWnd = this.Handle;
abd.uEdge = (int)ABEdge.ABE_TOP;
if (abd.uEdge == (int)ABEdge.ABE_LEFT || abd.uEdge == (int)ABEdge.ABE_RIGHT)
{
abd.rc.top = 0;
abd.rc.bottom = SystemInformation.PrimaryMonitorSize.Height;
if (abd.uEdge == (int)ABEdge.ABE_LEFT)
{
abd.rc.left = 0;
abd.rc.right = Size.Width;
}
else
{
abd.rc.right = SystemInformation.PrimaryMonitorSize.Width;
abd.rc.left = abd.rc.right - Size.Width;
}
}
else
{
abd.rc.left = 0;
abd.rc.right = SystemInformation.PrimaryMonitorSize.Width;
if (abd.uEdge == (int)ABEdge.ABE_TOP)
{
abd.rc.top = 0;
abd.rc.bottom = Size.Height;
}
else
{
abd.rc.bottom = SystemInformation.PrimaryMonitorSize.Height;
abd.rc.top = abd.rc.bottom - Size.Height;
}
}
You can use a different screen by iterating over the Screen.AllScreens array. For example, here is how you would get the first non-primary monitor:
Screen nonPrimaryScreen = Screen.AllScreens.FirstOrDefault(x => !x.Primary);
Then everywhere you are using SystemInformation.WorkingArea (which always uses the primary screen), you can use:
nonPrimaryScreen.WorkingArea
Assuming nonPrimaryScreen != null ... of course.
EDIT:
Instead of duplicating code, make it all more generic:
public static Rectangle GetWorkingArea() {
if (UseWantsItOnPrimaryScreen) {
return SystemInformation.WorkingArea;
}
else {
return Screen.AllScreens.FirstOrDefault(x => !x.Primary).WorkingArea;
}
}
private Screen GetScreenObject(String Name)
{
logger.Info(GlobalModulename + "# ScreenList::looking for screen:"+Name);
if ((Name == "Primary"))
{
bool ExpectedParameter = true;
foreach (var screen in Screen.AllScreens)
{
// For each screen, add the screen properties to a list box.
logger.Info(GlobalModulename + "# ScreenList::("+screen.DeviceName.ToString()+")Primary Screen: " + screen.Primary.ToString());
if (screen.Primary==ExpectedParameter)
{
return screen;
}
}
}
if ((Name == "Secondary"))
{
bool ExpectedParameter = false;
foreach (var screen in Screen.AllScreens)
{
// For each screen, add the screen properties to a list box.
logger.Info(GlobalModulename + "# ScreenList::(" + screen.DeviceName.ToString() + ")Primary Screen: " + screen.Primary.ToString());
if (screen.Primary == ExpectedParameter)
{
return screen;
}
}
}
// konkretni jmeno obrazovky tak jak je to v systemu
try
{
foreach (var screen in Screen.AllScreens)
{
// For each screen, add the screen properties to a list box.
logger.Info("UEFA_Core # ScreenList::Device Name: " + screen.DeviceName);
logger.Info("UEFA_Core # ScreenList::Bounds: " + screen.Bounds.ToString());
logger.Info("UEFA_Core # ScreenList::Type: " + screen.GetType().ToString());
logger.Info("UEFA_Core # ScreenList::Working Area: " + screen.WorkingArea.ToString());
logger.Info("UEFA_Core # ScreenList::Primary Screen: " + screen.Primary.ToString());
if (screen.DeviceName == Name) return screen;
}
}
catch { }
// podobne jmeno obrazovky tak jak je to v systemu
try
{
foreach (var screen in Screen.AllScreens)
{
// For each screen, add the screen properties to a list box.
logger.Info("UEFA_Core # ScreenList::Device Name: " + screen.DeviceName);
logger.Info("UEFA_Core # ScreenList::Bounds: " + screen.Bounds.ToString());
logger.Info("UEFA_Core # ScreenList::Type: " + screen.GetType().ToString());
logger.Info("UEFA_Core # ScreenList::Working Area: " + screen.WorkingArea.ToString());
logger.Info("UEFA_Core # ScreenList::Primary Screen: " + screen.Primary.ToString());
if (screen.DeviceName.Contains(Name)) return screen;
}
}
catch { }
logger.Info("UEFA_Core # ScreenList::No screen found by name");
return Screen.PrimaryScreen;
}
#region APPBAR
[StructLayout(LayoutKind.Sequential)]
struct RECT
{
public int left;
public int top;
public int right;
public int bottom;
}
[StructLayout(LayoutKind.Sequential)]
struct APPBARDATA
{
public int cbSize;
public IntPtr hWnd;
public int uCallbackMessage;
public int uEdge;
public RECT rc;
public IntPtr lParam;
}
enum ABMsg : int
{
ABM_NEW = 0,
ABM_REMOVE = 1,
ABM_QUERYPOS = 2,
ABM_SETPOS = 3,
ABM_GETSTATE = 4,
ABM_GETTASKBARPOS = 5,
ABM_ACTIVATE = 6,
ABM_GETAUTOHIDEBAR = 7,
ABM_SETAUTOHIDEBAR = 8,
ABM_WINDOWPOSCHANGED = 9,
ABM_SETSTATE = 10
}
enum ABNotify : int
{
ABN_STATECHANGE = 0,
ABN_POSCHANGED,
ABN_FULLSCREENAPP,
ABN_WINDOWARRANGE
}
enum ABEdge : int
{
ABE_LEFT = 0,
ABE_TOP,
ABE_RIGHT,
ABE_BOTTOM
}
private bool fBarRegistered = false;
[DllImport("SHELL32", CallingConvention = CallingConvention.StdCall)]
static extern uint SHAppBarMessage(int dwMessage, ref APPBARDATA pData);
[DllImport("USER32")]
static extern int GetSystemMetrics(int Index);
[DllImport("User32.dll", ExactSpelling = true,
CharSet = System.Runtime.InteropServices.CharSet.Auto)]
private static extern bool MoveWindow
(IntPtr hWnd, int x, int y, int cx, int cy, bool repaint);
[DllImport("User32.dll", CharSet = CharSet.Auto)]
private static extern int RegisterWindowMessage(string msg);
private int uCallBack;
private void RegisterBar()
{
APPBARDATA abd = new APPBARDATA();
abd.cbSize = Marshal.SizeOf(abd);
abd.hWnd = this.Handle;
if (!fBarRegistered)
{
uCallBack = RegisterWindowMessage("AppBarMessage");
abd.uCallbackMessage = uCallBack;
uint ret = SHAppBarMessage((int)ABMsg.ABM_NEW, ref abd);
fBarRegistered = true;
ABSetPos();
}
else
{
SHAppBarMessage((int)ABMsg.ABM_REMOVE, ref abd);
fBarRegistered = false;
}
}
private void ABSetPos()
{
APPBARDATA abd = new APPBARDATA();
abd.cbSize = Marshal.SizeOf(abd);
abd.hWnd = this.Handle;
abd.uEdge = (int)ABEdge.ABE_TOP;
if (abd.uEdge == (int)ABEdge.ABE_LEFT || abd.uEdge == (int)ABEdge.ABE_RIGHT)
{
abd.rc.top = this.GetScreenObject(ScreenName).Bounds.Top; //0;
abd.rc.bottom = this.GetScreenObject(ScreenName).Bounds.Top + this.GetScreenObject(ScreenName).Bounds.Height; //SystemInformation.PrimaryMonitorSize.Height;
if (abd.uEdge == (int)ABEdge.ABE_LEFT)
{
abd.rc.left = this.GetScreenObject(ScreenName).Bounds.Left;//0;
abd.rc.right = Size.Width;
}
else
{
abd.rc.right = this.GetScreenObject(ScreenName).Bounds.Left + this.GetScreenObject(ScreenName).Bounds.Width; // SystemInformation.PrimaryMonitorSize.Width;
abd.rc.left = abd.rc.right - Size.Width;
}
}
else
{
abd.rc.left = this.GetScreenObject(ScreenName).Bounds.Left; //0;
abd.rc.right = this.GetScreenObject(ScreenName).Bounds.Left+this.GetScreenObject(ScreenName).Bounds.Width; //SystemInformation.PrimaryMonitorSize.Width;
if (abd.uEdge == (int)ABEdge.ABE_TOP)
{
abd.rc.top = this.GetScreenObject(ScreenName).Bounds.Top; //0 nebo -1080
abd.rc.bottom = Size.Height;
}
else
{
abd.rc.bottom = this.GetScreenObject(ScreenName).Bounds.Top + this.GetScreenObject(ScreenName).Bounds.Height; //SystemInformation.PrimaryMonitorSize.Height;
abd.rc.top = abd.rc.bottom - Size.Height;
}
}
// Query the system for an approved size and position.
SHAppBarMessage((int)ABMsg.ABM_QUERYPOS, ref abd);
// Adjust the rectangle, depending on the edge to which the
// appbar is anchored.
switch (abd.uEdge)
{
case (int)ABEdge.ABE_LEFT:
abd.rc.right = abd.rc.left + Size.Width;
break;
case (int)ABEdge.ABE_RIGHT:
abd.rc.left = abd.rc.right - Size.Width;
break;
case (int)ABEdge.ABE_TOP:
abd.rc.bottom = abd.rc.top + Size.Height;
break;
case (int)ABEdge.ABE_BOTTOM:
abd.rc.top = abd.rc.bottom - Size.Height;
break;
}
// Pass the final bounding rectangle to the system.
SHAppBarMessage((int)ABMsg.ABM_SETPOS, ref abd);
// Move and size the appbar so that it conforms to the
// bounding rectangle passed to the system.
MoveWindow(abd.hWnd, abd.rc.left, abd.rc.top,
abd.rc.right - abd.rc.left, abd.rc.bottom - abd.rc.top, true);
}
protected override void WndProc(ref System.Windows.Forms.Message m)
{
if (m.Msg == uCallBack)
{
switch (m.WParam.ToInt32())
{
case (int)ABNotify.ABN_POSCHANGED:
ABSetPos();
break;
}
}
try
{
base.WndProc(ref m);
}
catch (Exception E) { }
}
protected override System.Windows.Forms.CreateParams CreateParams
{
get
{
CreateParams cp = base.CreateParams;
cp.Style &= (~0x00C00000); // WS_CAPTION
cp.Style &= (~0x00800000); // WS_BORDER
//cp.ExStyle = 0x00000080 | 0x00000008 | 0x20; // WS_EX_TOOLWINDOW | WS_EX_TOPMOST
//cp.ExStyle &= 0x20;
cp.ExStyle |= 0x00000008 | 0x00000080;
//cp.ExStyle &= 0x00000080 ; // WS_EX_TOOLWINDOW | WS_EX_TOPMOST
return cp;
}
}
private void OnLoad(object sender, System.EventArgs e)
{
RegisterBar();
}
private void OnClosing(object sender, System.ComponentModel.CancelEventArgs e)
{
RegisterBar();
}
#endregion
You can compute correct formula for moving your AppBar to second monitor without using anything other than PrimaryMonitorSize. For example for left side AppBar on second monitor you can use this:
if (abd.uEdge == (int)ABEdge.ABE_LEFT)
{
abd.rc.left = SystemInformation.PrimaryMonitorSize.Width;
abd.rc.right = SystemInformation.PrimaryMonitorSize.Width + Size.Width;
}

Categories