C# error on build - c#

Hi I am getting an 'Inconsistent accessibility: parameter type'clsWebCamArgs' is less accessible than delegate 'ctrlCamera.WebCamEventHandler'. Can anyone give any insight as to whats wrong with the code below.
using System;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace PayrollSystem
{
[ToolboxBitmap(typeof(ctrlCamera), "Camera.ico")] // toolbox bitmap
[Designer("Sytem.Windows.Forms.Design.ParentControlDesigner,System.Design", typeof(IDesigner))] // make composite
public partial class ctrlCamera : UserControl
{
public ctrlCamera(){InitializeComponent();}
// property variables
private int m_TimeToCapture_milliseconds = 100;
private int m_Width = 320;
private int m_Height = 240;
private int mCapHwnd;
private ulong m_FrameNumber = 0;
// global variables to make the video capture go faster
private PayrollSystem.clsWebCamArgs x = new PayrollSystem.clsWebCamArgs();
private IDataObject tempObj;
private Image tempImg;
private bool bStopped = true;
// event delegate
public delegate void WebCamEventHandler(object source, PayrollSystem.clsWebCamArgs e);
// fired when a new image is captured
public event WebCamEventHandler ImageCaptured;
#region API Declarations
[DllImport("user32", EntryPoint = "SendMessage")]
public static extern int SendMessage(int hWnd, uint Msg, int wParam, int lParam);
[DllImport("avicap32.dll", EntryPoint = "capCreateCaptureWindowA")]
public static extern int capCreateCaptureWindowA(string lpszWindowName, int dwStyle, int X, int Y, int nWidth, int nHeight, int hwndParent, int nID);
[DllImport("user32", EntryPoint = "OpenClipboard")]
public static extern int OpenClipboard(int hWnd);
[DllImport("user32", EntryPoint = "EmptyClipboard")]
public static extern int EmptyClipboard();
[DllImport("user32", EntryPoint = "CloseClipboard")]
public static extern int CloseClipboard();
#endregion
#region API Constants
public const int WM_USER = 1024;
public const int WM_CAP_CONNECT = 1034;
public const int WM_CAP_DISCONNECT = 1035;
public const int WM_CAP_GET_FRAME = 1084;
public const int WM_CAP_COPY = 1054;
public const int WM_CAP_START = WM_USER;
public const int WM_CAP_DLG_VIDEOFORMAT = WM_CAP_START + 41;
public const int WM_CAP_DLG_VIDEOSOURCE = WM_CAP_START + 42;
public const int WM_CAP_DLG_VIDEODISPLAY = WM_CAP_START + 43;
public const int WM_CAP_GET_VIDEOFORMAT = WM_CAP_START + 44;
public const int WM_CAP_SET_VIDEOFORMAT = WM_CAP_START + 45;
public const int WM_CAP_DLG_VIDEOCOMPRESSION = WM_CAP_START + 46;
public const int WM_CAP_SET_PREVIEW = WM_CAP_START + 50;
#endregion
#region Control Properties
public int TimeToCapture_milliseconds
{
get { return m_TimeToCapture_milliseconds; }
set { m_TimeToCapture_milliseconds = value; }
}
public int CaptureHeight
{
get { return m_Height; }
set { m_Height = value; }
}
public int CaptureWidth
{
get { return m_Width; }
set { m_Width = value; }
}
public ulong FrameNumber
{
get { return m_FrameNumber; }
set { m_FrameNumber = value; }
}
#endregion
#region Start and Stop Capture Functions
public void Start(ulong FrameNum)
{
try
{
// for safety, call stop, just in case we are already running
this.Stop();
// setup a capture window
mCapHwnd = capCreateCaptureWindowA("WebCap", 0, 0, 0, m_Width, m_Height, this.Handle.ToInt32(), 0);
// connect to the capture device
Application.DoEvents();
SendMessage(mCapHwnd, WM_CAP_CONNECT, 0, 0);
SendMessage(mCapHwnd, WM_CAP_SET_PREVIEW, 0, 0);
// set the frame number
m_FrameNumber = FrameNum;
// set the timer information
this.timer1.Interval = m_TimeToCapture_milliseconds;
bStopped = false;
this.timer1.Start();
}
catch (Exception excep)
{
MessageBox.Show("An error ocurred while starting the video capture. Check that your webcamera is connected properly and turned on.\r\n\n" + excep.Message);
this.Stop();
}
}
public void Stop()
{
try
{
// stop the timer
bStopped = true;
this.timer1.Stop();
// disconnect from the video source
Application.DoEvents();
SendMessage(mCapHwnd, WM_CAP_DISCONNECT, 0, 0);
}
catch (Exception excep)
{ // don't raise an error here.
}
}
#endregion
#region Video Capture Code
private void timer1_Tick(object sender, EventArgs e)
{
try
{
// pause the timer
this.timer1.Stop();
// get the next frame;
SendMessage(mCapHwnd, WM_CAP_GET_FRAME, 0, 0);
// copy the frame to the clipboard
SendMessage(mCapHwnd, WM_CAP_COPY, 0, 0);
// paste the frame into the event args image
if (ImageCaptured != null)
{
// get from the clipboard
tempObj = Clipboard.GetDataObject();
tempImg = (Bitmap)tempObj.GetData(DataFormats.Bitmap);
x.WebCamImage = tempImg.GetThumbnailImage(m_Width, m_Height, null, IntPtr.Zero);
// raise the event
this.ImageCaptured(this, x);
}
// restart the timer
Application.DoEvents();
if (!bStopped)
this.timer1.Start();
}
catch (Exception excep)
{
MessageBox.Show("An error ocurred while capturing the video image. The video capture will now be terminated.\r\n\n" + excep.Message);
this.Stop(); // stop the process
}
}
#endregion
}
}

You declare
public delegate void WebCamEventHandler(object source, PayrollSystem.clsWebCamArgs e);
as public, meaning it should be accessible from everywhere (even from other assemblies).
But it seems (though I can't find it the code you show) that PayrollSystem.clsWebCamArgs are not declared public, and so not as accessible as the delegate.
So the compiler is giving you an error, because it's not possible to access WebCamEventHandler from other assemblies if the type of one of it's arguments is not accessible.
To solve this, you can either change the declaration of WebCamEventHandler to internal or the declaration of clsWebCamArgs to public.

Related

how to connect mobile camera or other camera to the picture box in c#,winforms?

Started learning c# from past 1 month,I have a question that whether is it possibility to connect and display mobile camera or other web camera in the picture box.,in c# .net framework in windows forms. thanks in advance
You question is a bit too broad for this site. The answer is "Yes it is possible" but it is not as simple as writing a few lines of code in C#. You will need some kind of toolkit/library/framework that allows you to connect to the camera and display the video. There are tons of them out there, each having pros and cons, some simple, some complicated.
If you are using Visual Studio, in the Solution Explorer right-click on your Project name and select "Manage Nuget Packages". In the Window that opens select "Browse" and then type "camera" into the search box. You will see a number of packages that provide support for using cameras.
There are several ways to communicate with the camera.
I use this code to communicate with the camera.
public class CameraAPI
{
public bool IsAvailable { get; set; }
[DllImport("avicap32.dll")]
public static extern IntPtr capCreateCaptureWindowA(byte[] lpszWindowName, int dwStyle, int x, int y, int nWidth, int nHeight, IntPtr hWndParent, int nID);
[DllImport("avicap32.dll")]
public static extern bool capGetDriverDescriptionA(short wDriver, byte[] lpszName, int cbName, byte[] lpszVer, int cbVer);
[DllImport("User32.dll")]
public static extern bool SendMessage(IntPtr hWnd, int wMsg, bool wParam, long lParam);
[DllImport("User32.dll")]
public static extern bool SendMessage(IntPtr hWnd, int wMsg, short wParam, long lParam);
[System.Runtime.InteropServices.DllImport("user32")]
public static extern bool DestroyWindow(IntPtr hWnd);
public const int WM_USER = 0x400;
public const int WS_CHILD = 0x40000000;
public const int WS_VISIBLE = 0x10000000;
public const int SWP_NOMOVE = 0x2;
public const int SWP_NOZORDER = 0x4;
public const int WM_CAP_DRIVER_CONNECT = WM_USER + 10;
public const int WM_CAP_DRIVER_DISCONNECT = WM_USER + 11;
public const int WM_CAP_SET_CALLBACK_FRAME = WM_USER + 5;
public const int WM_CAP_SET_PREVIEW = WM_USER + 50;
public const int WM_CAP_SET_PREVIEWFORMAT = WM_USER + 45;
public const int WM_CAP_SET_PREVIEWRATE = WM_USER + 52;
public const int WM_CAP_START = WM_USER;
public const int WM_CAP_SAVEDIB = WM_CAP_START + 25;
public const int WM_CAP_EDIT_COPY = (WM_CAP_START + 30);
private IntPtr hWnd;
private IntPtr mControlPtr;
private int mWidth;
private int mHeight;
public CameraAPI(IntPtr handel, int width, int height)
{
mControlPtr = handel; //handle of video dom
mWidth = width; //video width
mHeight = height; //video height
}
public void StartPreviewWebcam()
{
if (hWnd != null)
DestroyWindow(hWnd);
byte[] lpszName = new byte[100];
byte[] lpszVer = new byte[100];
capGetDriverDescriptionA(0, lpszName, 100, lpszVer, 0);
hWnd = capCreateCaptureWindowA(lpszName, WS_CHILD | WS_VISIBLE, 0, 0, mWidth, mHeight, mControlPtr, 0);
if (SendMessage(hWnd, WM_CAP_DRIVER_CONNECT, 0, 0))
{
SendMessage(hWnd, WM_CAP_SET_PREVIEWRATE, 100, 0);
SendMessage(hWnd, WM_CAP_SET_PREVIEW, true, 0);
IsAvailable = true;
}
else
{
IsAvailable = false;
}
}
public void CloseWebcam()
{
SendMessage(hWnd, WM_CAP_DRIVER_DISCONNECT, 0, 0);
IsAvailable = false;
}
public void SavePictureByPath(string path)
{
IntPtr hBmp = Marshal.StringToHGlobalAnsi(path);
SendMessage(hWnd, WM_CAP_SAVEDIB, 0, hBmp.ToInt64());
}
public byte[] TakePicture()
{
byte[] imgByteArray = null;
var path = Application.StartupPath + #"\Image.png";
try
{
DeleteExist(path);
SavePictureByPath(path);
if (File.Exists(path))
{
using (Image img = Image.FromFile(path))
{
imgByteArray = ImageToByteArray(img);
}
}
}
catch (Exception exp)
{
var a = 1;
}
finally
{
DeleteExist(path);
}
return imgByteArray;
}
public void DeleteExist(string path)
{
if (File.Exists(path))
{
File.Delete(path);
}
}
public byte[] ImageToByteArray(System.Drawing.Image imageIn)
{
using (var ms = new MemoryStream())
{
imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
return ms.ToArray();
}
}
}

Full screen windows form but with title bar

I am following this article, http://www.vesic.org/english/blog-eng/net/full-screen-maximize/
This makes my windows form to go full screen but it also hides Title bar.
I want to hide task bar but like to have my title bar.
" targetForm.FormBorderStyle = FormBorderStyle.None;" hides my title bar but removing this shows task bar so is there anyway to hide task bar and keep title bar in windows app? Thanks
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace myClasses
{
public class WinApi
{
[DllImport("user32.dll", EntryPoint = "GetSystemMetrics")]
public static extern int GetSystemMetrics(int which);
[DllImport("user32.dll")]
public static extern void
SetWindowPos(IntPtr hwnd, IntPtr hwndInsertAfter,
int X, int Y, int width, int height, uint flags);
private const int SM_CXSCREEN = 0;
private const int SM_CYSCREEN = 1;
private static IntPtr HWND_TOP = IntPtr.Zero;
private const int SWP_SHOWWINDOW = 64; // 0x0040
public static int ScreenX
{
get { return GetSystemMetrics(SM_CXSCREEN); }
}
public static int ScreenY
{
get { return GetSystemMetrics(SM_CYSCREEN); }
}
public static void SetWinFullScreen(IntPtr hwnd)
{
SetWindowPos(hwnd, HWND_TOP, 0, 0, ScreenX, ScreenY, SWP_SHOWWINDOW);
}
}
/// <summary>
/// Class used to preserve / restore state of the form
/// </summary>
public class FormState
{
private FormWindowState winState = FormWindowState.Normal;
private FormBorderStyle brdStyle = FormBorderStyle.Sizable;
private bool topMost;
private Rectangle bounds;
private bool IsMaximized = false;
public void Maximize(Form targetForm)
{
if (!IsMaximized)
{
IsMaximized = true;
Save(targetForm);
targetForm.WindowState = FormWindowState.Maximized;
targetForm.FormBorderStyle = FormBorderStyle.None;
//targetForm.TopMost = true;
WinApi.SetWinFullScreen(targetForm.Handle);
}
}
public void Save(Form targetForm)
{
winState = targetForm.WindowState;
brdStyle = targetForm.FormBorderStyle;
topMost = targetForm.TopMost;
bounds = targetForm.Bounds;
}
public void Restore(Form targetForm)
{
targetForm.WindowState = winState;
targetForm.FormBorderStyle = brdStyle;
targetForm.TopMost = topMost;
targetForm.Bounds = bounds;
IsMaximized = false;
}
}
}
You can set it to FormBorderStyle.FixedToolWindow;, than only the taskbar is hidden.

How to programmatically set the system volume?

How can I change the Windows System Sound Volume using a C# Application?
I'm a bit late to the party but if you are looking now there's a nuget package available (AudioSwitcher.AudioApi.CoreAudio) that simplifies audio interactions. Install it then it’s as simple as:
CoreAudioDevice defaultPlaybackDevice = new CoreAudioController().DefaultPlaybackDevice;
Debug.WriteLine("Current Volume:" + defaultPlaybackDevice.Volume);
defaultPlaybackDevice.Volume = 80;
Here is the code:
using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace Test
{
public class Test
{
private const int APPCOMMAND_VOLUME_MUTE = 0x80000;
private const int APPCOMMAND_VOLUME_UP = 0xA0000;
private const int APPCOMMAND_VOLUME_DOWN = 0x90000;
private const int WM_APPCOMMAND = 0x319;
[DllImport("user32.dll")]
public static extern IntPtr SendMessageW(IntPtr hWnd, int Msg,
IntPtr wParam, IntPtr lParam);
private void Mute()
{
SendMessageW(this.Handle, WM_APPCOMMAND, this.Handle,
(IntPtr)APPCOMMAND_VOLUME_MUTE);
}
private void VolDown()
{
SendMessageW(this.Handle, WM_APPCOMMAND, this.Handle,
(IntPtr)APPCOMMAND_VOLUME_DOWN);
}
private void VolUp()
{
SendMessageW(this.Handle, WM_APPCOMMAND, this.Handle,
(IntPtr)APPCOMMAND_VOLUME_UP);
}
}
}
Found on dotnetcurry
When using WPF you need to use new WindowInteropHelper(this).Handle instead of this.Handle (thanks Alex Beals)
If the tutorials provided in the other answers are too involved you could try an implementation like this using the keybd_event function
[DllImport("user32.dll")]
static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, int dwExtraInfo);
Usage:
keybd_event((byte)Keys.VolumeUp, 0, 0, 0); // increase volume
keybd_event((byte)Keys.VolumeDown, 0, 0, 0); // decrease volume
In case you wish to set it to an exact value using the Core Audio APIs:
using CoreAudioApi;
public class SystemVolumeConfigurator
{
private readonly MMDeviceEnumerator _deviceEnumerator = new MMDeviceEnumerator();
private readonly MMDevice _playbackDevice;
public SystemVolumeConfigurator()
{
_playbackDevice = _deviceEnumerator.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia);
}
public int GetVolume()
{
return (int)(_playbackDevice.AudioEndpointVolume.MasterVolumeLevelScalar * 100);
}
public void SetVolume(int volumeLevel)
{
if (volumeLevel < 0 || volumeLevel > 100)
throw new ArgumentException("Volume must be between 0 and 100!");
_playbackDevice.AudioEndpointVolume.MasterVolumeLevelScalar = volumeLevel / 100.0f;
}
}
You can add this library https://gist.github.com/sverrirs/d099b34b7f72bb4fb386 to your project and change the volume like this;
VideoPlayerController.AudioManager.SetMasterVolume(100);
The library also includes options for changing application volume, mute, getting current volume level etc.
The namespace is called "Video Player Controller" but I used it in a Windows Forms App to change the system volume and it worked fine, so the "video" part is arbitrary.
C# code:
[Guid("5CDF2C82-841E-4546-9722-0CF74078229A"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface IAudioEndpointVolume
{
int _0(); int _1(); int _2(); int _3();
int SetMasterVolumeLevelScalar(float fLevel, Guid pguidEventContext);
int _5();
int GetMasterVolumeLevelScalar(out float pfLevel);
int _7(); int _8(); int _9(); int _10(); int _11(); int _12();
}
[Guid("D666063F-1587-4E43-81F1-B948E807363F"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface IMMDevice
{
int Activate(ref System.Guid id, int clsCtx, int activationParams, out IAudioEndpointVolume aev);
}
[Guid("A95664D2-9614-4F35-A746-DE8DB63617E6"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface IMMDeviceEnumerator
{
int _0();
int GetDefaultAudioEndpoint(int dataFlow, int role, out IMMDevice endpoint);
}
[ComImport, Guid("BCDE0395-E52F-467C-8E3D-C4579291692E")] class MMDeviceEnumeratorComObject { }
public class Audio
{
private static readonly IAudioEndpointVolume _MMVolume;
static Audio()
{
var enumerator = new MMDeviceEnumeratorComObject() as IMMDeviceEnumerator;
enumerator.GetDefaultAudioEndpoint(0, 1, out IMMDevice dev);
var aevGuid = typeof(IAudioEndpointVolume).GUID;
dev.Activate(ref aevGuid, 1, 0, out _MMVolume);
}
public static int Volume
{
get
{
_MMVolume.GetMasterVolumeLevelScalar(out float level);
return (int)(level * 100);
}
set
{
_MMVolume.SetMasterVolumeLevelScalar((float)value / 100, default);
}
}
}
Usage:
Audio.Volume = 50;
More info on MSDN.
My code is a bit different but still using CoreAudio
downloaded the pkg :
nuget install AudioSwitcher.AudioApi.CoreAudio -Version 3.0.0.1
using AudioSwitcher.AudioApi.CoreAudio;
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
CoreAudioDevice defaultPlaybackDevice = new CoreAudioController().DefaultPlaybackDevice;
double vol = defaultPlaybackDevice.Volume;
defaultPlaybackDevice.Volume = defaultPlaybackDevice.Volume - 5.0;
defaultPlaybackDevice.Volume = defaultPlaybackDevice.Volume + 5.0;
}
}

TreeView custom DrawNode .NET 3.5 Windows Forms

I want to customize DrawNode in OwnerDrawText mode in a TreeView. I found it very slow even with this handler:
void RegistryTreeDrawNode(object sender, DrawTreeNodeEventArgs e)
{
e.DrawDefault = true;
}
Am I doing something wrong?
Thanks.
I think you may need to show a bit more code for what you're trying to do. There shouldn't be anything noticeably different drawing like that, versus not owner drawing at all; you're basically overriding the default draw and then undoing it in what you posted. It's ugly for no gain... but shouldn't be a perf hit.
So switching away from the lack of code and going after your core desire of a custom drawn tree, let me tell you that there is NOT a lot of good information out in the wild right now.
I've been doing my own custom treeview work over the past few days and will probably end up writing a tutorial on all that I've learned. In the meantime feel free to take a look at my code and see if it helps you out.
Mine was simply a custom drawn explorer treeview. The code that populates the treeview is separate from the TreeView drawing code. You'll probably need to add your own +/- images if you wanted to run my code.
Utilities\IconReader.cs
using System;
using System.Runtime.InteropServices;
namespace TreeViewTestProject.Utilities
{
public class IconReader
{
public enum IconSize
{
Large = 0,
Small = 1
};
public enum FolderType
{
Open = 0,
Closed = 1
};
/// <summary>
/// Returns an icon for a given file - indicated by the name parameter.
/// </summary>
/// <param name="name">Pathname for file.</param>
/// <param name="size">Large or small</param>
/// <param name="linkOverlay">Whether to include the link icon</param>
/// <returns>System.Drawing.Icon</returns>
public static System.Drawing.Icon GetFileIcon(string name, IconSize size, bool linkOverlay)
{
Shell32.SHFILEINFO shfi = new Shell32.SHFILEINFO();
uint flags = Shell32.SHGFI_ICON | Shell32.SHGFI_USEFILEATTRIBUTES;
if(true == linkOverlay) flags |= Shell32.SHGFI_LINKOVERLAY;
/* Check the size specified for return. */
if(IconSize.Small == size)
{
flags |= Shell32.SHGFI_SMALLICON;
}
else
{
flags |= Shell32.SHGFI_LARGEICON;
}
Shell32.SHGetFileInfo(name,
Shell32.FILE_ATTRIBUTE_NORMAL,
ref shfi,
(uint)System.Runtime.InteropServices.Marshal.SizeOf(shfi),
flags);
// Copy (clone) the returned icon to a new object, thus allowing us to clean-up properly
System.Drawing.Icon icon = (System.Drawing.Icon)System.Drawing.Icon.FromHandle(shfi.hIcon).Clone();
User32.DestroyIcon(shfi.hIcon); // Cleanup
return icon;
}
/// <summary>
/// Used to access system folder icons.
/// </summary>
/// <param name="size">Specify large or small icons.</param>
/// <param name="folderType">Specify open or closed FolderType.</param>
/// <returns>System.Drawing.Icon</returns>
public static System.Drawing.Icon GetFolderIcon(string Foldername, IconSize size, FolderType folderType)
{
// Need to add size check, although errors generated at present!
uint flags = Shell32.SHGFI_ICON | Shell32.SHGFI_USEFILEATTRIBUTES;
if(FolderType.Open == folderType)
{
flags |= Shell32.SHGFI_OPENICON;
}
if(IconSize.Small == size)
{
flags |= Shell32.SHGFI_SMALLICON;
}
else
{
flags |= Shell32.SHGFI_LARGEICON;
}
// Get the folder icon
Shell32.SHFILEINFO shfi = new Shell32.SHFILEINFO();
Shell32.SHGetFileInfo(Foldername,
Shell32.FILE_ATTRIBUTE_DIRECTORY,
ref shfi,
(uint)System.Runtime.InteropServices.Marshal.SizeOf(shfi),
flags);
System.Drawing.Icon.FromHandle(shfi.hIcon); // Load the icon from an HICON handle
// Now clone the icon, so that it can be successfully stored in an ImageList
System.Drawing.Icon icon = (System.Drawing.Icon)System.Drawing.Icon.FromHandle(shfi.hIcon).Clone();
User32.DestroyIcon(shfi.hIcon); // Cleanup
return icon;
}
}
public class Shell32
{
public const int MAX_PATH = 256;
[StructLayout(LayoutKind.Sequential)]
public struct SHITEMID
{
public ushort cb;
[MarshalAs(UnmanagedType.LPArray)]
public byte[] abID;
}
[StructLayout(LayoutKind.Sequential)]
public struct ITEMIDLIST
{
public SHITEMID mkid;
}
[StructLayout(LayoutKind.Sequential)]
public struct BROWSEINFO
{
public IntPtr hwndOwner;
public IntPtr pidlRoot;
public IntPtr pszDisplayName;
[MarshalAs(UnmanagedType.LPTStr)]
public string lpszTitle;
public uint ulFlags;
public IntPtr lpfn;
public int lParam;
public IntPtr iImage;
}
// Browsing for directory.
public const uint BIF_RETURNONLYFSDIRS = 0x0001;
public const uint BIF_DONTGOBELOWDOMAIN = 0x0002;
public const uint BIF_STATUSTEXT = 0x0004;
public const uint BIF_RETURNFSANCESTORS = 0x0008;
public const uint BIF_EDITBOX = 0x0010;
public const uint BIF_VALIDATE = 0x0020;
public const uint BIF_NEWDIALOGSTYLE = 0x0040;
public const uint BIF_USENEWUI = (BIF_NEWDIALOGSTYLE | BIF_EDITBOX);
public const uint BIF_BROWSEINCLUDEURLS = 0x0080;
public const uint BIF_BROWSEFORCOMPUTER = 0x1000;
public const uint BIF_BROWSEFORPRINTER = 0x2000;
public const uint BIF_BROWSEINCLUDEFILES = 0x4000;
public const uint BIF_SHAREABLE = 0x8000;
[StructLayout(LayoutKind.Sequential)]
public struct SHFILEINFO
{
public const int NAMESIZE = 80;
public IntPtr hIcon;
public int iIcon;
public uint dwAttributes;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = MAX_PATH)]
public string szDisplayName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = NAMESIZE)]
public string szTypeName;
};
public const uint SHGFI_ICON = 0x000000100; // get icon
public const uint SHGFI_DISPLAYNAME = 0x000000200; // get display name
public const uint SHGFI_TYPENAME = 0x000000400; // get type name
public const uint SHGFI_ATTRIBUTES = 0x000000800; // get attributes
public const uint SHGFI_ICONLOCATION = 0x000001000; // get icon location
public const uint SHGFI_EXETYPE = 0x000002000; // return exe type
public const uint SHGFI_SYSICONINDEX = 0x000004000; // get system icon index
public const uint SHGFI_LINKOVERLAY = 0x000008000; // put a link overlay on icon
public const uint SHGFI_SELECTED = 0x000010000; // show icon in selected state
public const uint SHGFI_ATTR_SPECIFIED = 0x000020000; // get only specified attributes
public const uint SHGFI_LARGEICON = 0x000000000; // get large icon
public const uint SHGFI_SMALLICON = 0x000000001; // get small icon
public const uint SHGFI_OPENICON = 0x000000002; // get open icon
public const uint SHGFI_SHELLICONSIZE = 0x000000004; // get shell size icon
public const uint SHGFI_PIDL = 0x000000008; // pszPath is a pidl
public const uint SHGFI_USEFILEATTRIBUTES = 0x000000010; // use passed dwFileAttribute
public const uint SHGFI_ADDOVERLAYS = 0x000000020; // apply the appropriate overlays
public const uint SHGFI_OVERLAYINDEX = 0x000000040; // Get the index of the overlay
public const uint FILE_ATTRIBUTE_DIRECTORY = 0x00000010;
public const uint FILE_ATTRIBUTE_NORMAL = 0x00000080;
[DllImport("Shell32.dll")]
public static extern IntPtr SHGetFileInfo(
string pszPath,
uint dwFileAttributes,
ref SHFILEINFO psfi,
uint cbFileInfo,
uint uFlags
);
}
public class User32
{
/// <summary>
/// Provides access to function required to delete handle. This method is used internally
/// and is not required to be called separately.
/// </summary>
/// <param name="hIcon">Pointer to icon handle.</param>
/// <returns>N/A</returns>
[DllImport("User32.dll")]
public static extern int DestroyIcon(IntPtr hIcon);
}
}
ExplorerTreeView.cs :
using System;
using System.IO;
using System.Windows.Forms;
using TreeViewTestProject.Utilities;
using System.Collections;
namespace TreeViewTestProject
{
public partial class ExplorerTreeView : TreeViewEx
{
#region ExplorerNodeSorter Class
private class ExplorerNodeSorter : IComparer
{
public int Compare(object x, object y)
{
TreeNode nx = x as TreeNode;
TreeNode ny = y as TreeNode;
bool nxDir = (nx.ImageKey == kDirectoryImageKey);
bool nyDir = (ny.ImageKey == kDirectoryImageKey);
if(nxDir && !nyDir)
{
return -1;
}
else if(nyDir && !nxDir)
{
return 1;
}
else
{
return string.Compare(nx.Text, ny.Text);
}
}
}
#endregion
private const string kDirectoryImageKey = "directory";
private const string kReplacementText = "C43C65D1-D40F-46F0-BC5E-57265322DDFC";
public ExplorerTreeView()
{
InitializeComponent();
this.BeforeExpand += new TreeViewCancelEventHandler(ExplorerTreeView_BeforeExpand);
this.ImageList = m_FileIcons;
this.TreeViewNodeSorter = new ExplorerNodeSorter();
this.LabelEdit = true;
// Create the root of the tree and populate it
PopulateTreeView(#"C:\");
}
private void PopulateTreeView(string DirectoryName)
{
this.BeginUpdate();
string rootDir = DirectoryName;
TreeNode rootNode = CreateTreeNode(rootDir);
rootNode.Text = rootDir;
this.Nodes.Add(rootNode);
PopulateDirectory(rootNode);
this.EndUpdate();
}
private bool PathIsDirectory(string FullPath)
{
FileAttributes attr = File.GetAttributes(FullPath);
return ((attr & FileAttributes.Directory) == FileAttributes.Directory);
}
private TreeNode CreateTreeNode(string FullPath)
{
string key = FullPath.ToLower();
string name = "";
object tag = null;
if(PathIsDirectory(key))
{
DirectoryInfo info = new DirectoryInfo(FullPath);
key = kDirectoryImageKey;
name = info.Name;
tag = info;
}
else
{
FileInfo info = new FileInfo(FullPath);
name = info.Name;
tag = info;
}
if(!m_FileIcons.Images.ContainsKey(key))
{
if(key == "directory")
{
m_FileIcons.Images.Add(key, IconReader.GetFolderIcon(Environment.CurrentDirectory, IconReader.IconSize.Small, IconReader.FolderType.Open).ToBitmap());
}
else
{
m_FileIcons.Images.Add(key, IconReader.GetFileIcon(FullPath, IconReader.IconSize.Small, false));
}
}
TreeNode node = new TreeNode(name);
node.Tag = tag;
node.ImageKey = key;
node.SelectedImageKey = key;
return node;
}
private void PopulateDirectory(TreeNode ParentNode)
{
DirectoryInfo parentInfo = ParentNode.Tag as DirectoryInfo;
foreach(DirectoryInfo subDir in parentInfo.GetDirectories())
{
TreeNode child = CreateTreeNode(subDir.FullName);
PopulateForExpansion(child);
ParentNode.Nodes.Add(child);
}
foreach(FileInfo file in parentInfo.GetFiles())
{
ParentNode.Nodes.Add(CreateTreeNode(file.FullName));
}
}
private void PopulateForExpansion(TreeNode ParentNode)
{
// We need the +/- to show up if this directory isn't empty... but only want to populate the node on demand
DirectoryInfo parentInfo = ParentNode.Tag as DirectoryInfo;
try
{
if((parentInfo.GetDirectories().Length > 0) || (parentInfo.GetFiles().Length > 0))
{
ParentNode.Nodes.Add(kReplacementText);
}
}
catch { }
}
private void ReplacePlaceholderDirectoryNode(TreeNode ParentNode)
{
if((ParentNode.Nodes.Count == 1) && (ParentNode.Nodes[0].Text == kReplacementText))
{
ParentNode.Nodes.Clear();
PopulateDirectory(ParentNode);
}
}
private void ExplorerTreeView_BeforeExpand(object sender, TreeViewCancelEventArgs e)
{
this.BeginUpdate();
ReplacePlaceholderDirectoryNode(e.Node);
this.EndUpdate();
}
}
}
TreeViewEx.cs:
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace TreeViewTestProject
{
public partial class TreeViewEx : TreeView
{
// Notes: TextRenderer uses GDI to render the text, whereas Graphics uses GDI+. "TreeView" has existed for a long long time
// and thus uses GDI under the covers. For User Drawing TreeNode's, we need to make sure we use the TextRenderer version
// of text rendering functions.
#region Properties
private DashStyle m_SelectionDashStyle = DashStyle.Dot;
public DashStyle SelectionDashStyle
{
get { return m_SelectionDashStyle; }
set { m_SelectionDashStyle = value; }
}
private DashStyle m_LineStyle = DashStyle.Solid;
public DashStyle LineStyle
{
get { return m_LineStyle; }
set { m_LineStyle = value; }
}
private bool m_ShowLines = true;
public new bool ShowLines // marked as 'new' to replace base functionality fixing ShowLines/FullRowSelect issues in base.
{
get { return m_ShowLines; }
set { m_ShowLines = value; }
}
protected override CreateParams CreateParams
{
get
{
// Removes all the flickering of repainting node's
// This is the only thing I found that works properly for doublebuffering a treeview.
CreateParams cp = base.CreateParams;
cp.ExStyle |= 0x02000000; // WS_CLIPCHILDREN
return cp;
}
}
#endregion
[DllImport("user32.dll", ExactSpelling = false, CharSet = CharSet.Auto)]
private static extern int GetWindowLong(IntPtr hWnd, int nIndex);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
private static extern IntPtr SendMessage(HandleRef hWnd, uint Msg, IntPtr wParam, HandleRef lParam);
private const int GWL_STYLE = -16;
private const int WS_VSCROLL = 0x00200000;
private const uint TV_FIRST = 0x1100;
private const uint TVM_EDITLABELA = (TV_FIRST + 14);
private const uint TVM_EDITLABELW = (TV_FIRST + 65);
private bool m_SelectionChanged = false;
private bool m_DoubleClicked = false;
private bool m_HierarchyChanged = false;
public TreeViewEx()
{
InitializeComponent();
// ShowLines must be "false" for FullRowSelect to work - so we're overriding the variable to correct for that.
base.ShowLines = false;
this.FullRowSelect = true;
this.ItemHeight = 21;
this.DrawMode = TreeViewDrawMode.OwnerDrawAll;
this.DrawNode += OnDrawNode;
}
private void OnDrawNode(object sender, DrawTreeNodeEventArgs e)
{
e.DrawDefault = false;
if(e.Node.Bounds.IsEmpty) return;
// Clear out the previous contents for the node. If we don't do this, when you mousehover the font will get slightly more bold
Rectangle bounds = new Rectangle(0, e.Node.Bounds.Y, this.Width - 1, e.Node.Bounds.Height - 1);
e.Graphics.FillRectangle(SystemBrushes.Window, bounds);
// Draw everything
DrawNodeFocusedHighlight(e);
DrawNodeLines(e);
DrawPlusMinus(e);
DrawNodeIcon(e);
DrawNodeText(e);
}
private void DrawNodeFocusedHighlight(DrawTreeNodeEventArgs e)
{
if(SelectedNode != e.Node) return;
int scrollWidth = 0;
if(VScrollVisible())
{
scrollWidth = SystemInformation.VerticalScrollBarWidth;
}
Rectangle bounds = new Rectangle(0, e.Node.Bounds.Y, this.Width - scrollWidth, e.Node.Bounds.Height - 1);
if(!e.Node.IsEditing)
{
e.Graphics.FillRectangle(SystemBrushes.Highlight, bounds);
}
using(Pen focusPen = new Pen(Color.Black))
{
focusPen.DashStyle = SelectionDashStyle;
bounds = new Rectangle(0, e.Node.Bounds.Y, this.Width - scrollWidth - 5, e.Node.Bounds.Height - 2);
e.Graphics.DrawRectangle(focusPen, bounds);
}
}
private void DrawNodeText(DrawTreeNodeEventArgs e)
{
if(e.Node.Bounds.IsEmpty) return;
if(e.Node.IsEditing) return;
Rectangle bounds = e.Node.Bounds;
using(Font font = e.Node.NodeFont)
{
bounds.Width = TextRenderer.MeasureText(e.Node.Text, font).Width;
bounds.Y -= 1;
bounds.X += 1;
if(IsRootNode(e.Node))
{
bounds = new Rectangle(this.Margin.Size.Width + Properties.Resources.minus.Width + 9, 0, bounds.Width, bounds.Height);
}
Color fontColor = SystemColors.InactiveCaptionText;
if(this.Focused)
{
fontColor = e.Node.IsSelected?SystemColors.HighlightText:this.ForeColor;
}
TextRenderer.DrawText(e.Graphics, e.Node.Text, font, bounds, fontColor);
}
}
private bool IsRootNode(TreeNode Node)
{
return (Node.Level == 0 && Node.PrevNode == null);
}
private void DrawNodeLines(DrawTreeNodeEventArgs e)
{
DrawNodeLineVertical(e);
DrawNodeLineHorizontal(e);
}
private void DrawNodeLineVertical(DrawTreeNodeEventArgs e)
{
if(IsRootNode(e.Node)) return;
if(!ShowLines) return;
Pen linePen = new Pen(Color.Black);
linePen.DashStyle = LineStyle;
for(int x = 0; x < e.Node.Level; x++)
{
int xLoc = this.Indent + (x * this.Indent) + (Properties.Resources.minus.Width / 2);
int height = e.Bounds.Height;
if(ShouldDrawVerticalLineForLevel(e.Node, x))
{
e.Graphics.DrawLine(linePen, xLoc, e.Bounds.Top, xLoc, e.Bounds.Top + height);
}
}
// Draw the half line for the last node
if(e.Node.Parent.LastNode == e.Node)
{
int halfLoc = (e.Node.Level * this.Indent) + (Properties.Resources.minus.Width / 2);
e.Graphics.DrawLine(linePen, halfLoc, e.Bounds.Top, halfLoc, (e.Bounds.Top + e.Bounds.Height / 2) - 1);
}
}
private bool ShouldDrawVerticalLineForLevel(TreeNode Current, int Level)
{
TreeNode node = Current;
TreeNode c = Current;
while(node.Level != Level)
{
c = node;
node = node.Parent;
}
return !(node.LastNode == c);
}
private void DrawNodeLineHorizontal(DrawTreeNodeEventArgs e)
{
if(IsRootNode(e.Node)) return;
if(!ShowLines) return;
Pen linePen = new Pen(Color.Black);
int xLoc = (e.Node.Level * this.Indent) + (Properties.Resources.minus.Width / 2);
int midY = (e.Bounds.Top + e.Bounds.Bottom) / 2 - 1;
e.Graphics.DrawLine(linePen, xLoc, midY, xLoc + 7, midY);
}
private void DrawNodeIcon(DrawTreeNodeEventArgs e)
{
if(this.ImageList == null) return;
int indent = (e.Node.Level * this.Indent) + this.Margin.Size.Width;
int iconLeft = indent + this.Indent;
int imgIndex = this.ImageList.Images.IndexOfKey(e.Node.ImageKey);
if(!IsRootNode(e.Node))
{
if(imgIndex >= 0)
{
Image img = this.ImageList.Images[imgIndex];
int y = (e.Bounds.Y + e.Bounds.Height / 2) - (img.Height / 2) - 1;
e.Graphics.DrawImage(img, new Rectangle(iconLeft, y, img.Width, img.Height), new Rectangle(0, 0, img.Width, img.Height), GraphicsUnit.Pixel);
}
}
}
private void DrawPlusMinus(DrawTreeNodeEventArgs e)
{
if(e.Node.Nodes.Count == 0) return;
int indent = (e.Node.Level * this.Indent) + this.Margin.Size.Width;
int iconLeft = indent + this.Indent;
Image img = Properties.Resources.plus;
if(e.Node.IsExpanded) img = Properties.Resources.minus;
e.Graphics.DrawImage(img, iconLeft - img.Width - 2, (e.Bounds.Y + e.Bounds.Height / 2) - (img.Height / 2) - 1);
}
private bool VScrollVisible()
{
int style = GetWindowLong(this.Handle, GWL_STYLE);
return ((style & WS_VSCROLL) != 0);
}
private void BeginEditNode()
{
if(this.SelectedNode == null) return;
if(!this.LabelEdit) throw new Exception("This TreeView is not configured with LabelEdit=true");
IntPtr result = SendMessage(new HandleRef(this, this.Handle), TVM_EDITLABELA, IntPtr.Zero, new HandleRef(this.SelectedNode, this.SelectedNode.Handle));
if(result == IntPtr.Zero)
{
throw new Exception("Failed to send EDITLABEL message to TreeView control.");
}
}
private void TreeViewEx_BeforeLabelEdit(object sender, NodeLabelEditEventArgs e)
{
if(m_DoubleClicked)
{
m_DoubleClicked = false;
return;
}
if(m_SelectionChanged)
{
e.CancelEdit = true;
m_SelectionChanged = false;
}
}
private void TreeViewEx_MouseDoubleClick(object sender, MouseEventArgs e)
{
if(m_HierarchyChanged)
{
m_HierarchyChanged = false;
return;
}
if((e.Button & MouseButtons.Left) > 0)
{
if(this.LabelEdit && (this.SelectedNode != null))
{
m_DoubleClicked = true;
BeginInvoke(new MethodInvoker(delegate() { this.SelectedNode.BeginEdit(); }));
}
}
}
private void TreeViewEx_AfterCollapse(object sender, TreeViewEventArgs e)
{
m_HierarchyChanged = true;
}
private void TreeViewEx_AfterExpand(object sender, TreeViewEventArgs e)
{
m_HierarchyChanged = true;
}
}
}

Problem in hiding the taskbar using c#

i am using the below class to hid the task bar.
but the problem is, after hiding there is no focus in that place.
Its something like blocked. How to overcome this. Thanks.
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);
}
}
Are you trying to run a full screen application? If yes then read How To Cover the Task Bar with a Window and How To Make a Windows Form App Truly Full Screen (and Hide Taskbar) in C#
From the same article, you can use this code to run true full screen application
public class WinApi
{
[DllImport(”user32.dll”, EntryPoint = “GetSystemMetrics”)]
public static extern int GetSystemMetrics(int which);
[DllImport(”user32.dll”)]
public static extern void
SetWindowPos(IntPtr hwnd, IntPtr hwndInsertAfter,
int X, int Y, int width, int height, uint flags);
private const int SM_CXSCREEN = 0;
private const int SM_CYSCREEN = 1;
private static IntPtr HWND_TOP = IntPtr.Zero;
private const int SWP_SHOWWINDOW = 64; // 0×0040
public static int ScreenX
{
get { return GetSystemMetrics(SM_CXSCREEN);}
}
public static int ScreenY
{
get { return GetSystemMetrics(SM_CYSCREEN);}
}
public static void SetWinFullScreen(IntPtr hwnd)
{
SetWindowPos(hwnd, HWND_TOP, 0, 0, ScreenX, ScreenY, SWP_SHOWWINDOW);
}
}
Use this code:
public class FullScreenEngine
{
// Fields
private IntPtr _hWndInputPanel;
private IntPtr _hWndSipButton;
private IntPtr _hWndTaskBar;
private Rectangle _desktopArea;
public FullScreenEngine()
{
Init();
}
public bool SetFullScreen(bool mode)
{
try
{
if (mode)
{
if (_hWndTaskBar.ToInt64() != 0L)
{
ShowWindow(_hWndTaskBar, SW_HIDE);
}
if (_hWndInputPanel.ToInt64() != 0L)
{
ShowWindow(_hWndInputPanel, SW_HIDE);
}
if (_hWndSipButton.ToInt64() != 0L)
{
ShowWindow(_hWndSipButton, SW_HIDE);
}
WorkArea.SetWorkArea(new RECT(Screen.PrimaryScreen.Bounds));
}
else
{
if (_hWndTaskBar.ToInt64() != 0L)
{
ShowWindow(_hWndTaskBar, SW_SHOW);
}
if (_hWndInputPanel.ToInt64() != 0L)
{
//ShowWindow(_hWndInputPanel, SW_SHOW);
}
if (_hWndSipButton.ToInt64() != 0L)
{
ShowWindow(_hWndSipButton, SW_SHOW);
}
WorkArea.SetWorkArea(new RECT(_desktopArea));
}
}
catch (Exception)
{
return false;
}
return true;
}
private bool Init()
{
try
{
_desktopArea = Screen.PrimaryScreen.WorkingArea;
_hWndInputPanel = FindWindowW("SipWndClass", null);
_hWndSipButton = FindWindowW("MS_SIPBUTTON", null);
_hWndTaskBar = FindWindowW("HHTaskBar", null);
}
catch (Exception)
{
return false;
}
return true;
}
private const uint SW_HIDE = 0;
private const uint SW_SHOW = 1;
[DllImport("coredll.dll")]
private static extern int ShowWindow(IntPtr hwnd, uint command);
[DllImport("coredll.dll")]
private static extern IntPtr FindWindowW(string lpClassName, string lpWindowName);
// Nested Types
public struct RECT
{
public int Left;
public int Top;
public int Right;
public int Bottom;
public RECT(Rectangle rect) : this()
{
Left = rect.Left;
Right = rect.Left+rect.Width;
Top = rect.Top;
Bottom = rect.Top + rect.Height;
}
}
private static class WorkArea
{
[DllImport("coredll.dll")]
private static extern bool SystemParametersInfo(uint uAction, uint uparam, ref RECT rect, uint fuWinIni);
private const uint WM_SETTINGCHANGE = 0x1a;
const uint SPI_GETWORKAREA = 48;
const uint SPI_SETWORKAREA = 47;
public static bool SetWorkArea(RECT rect)
{
return SystemParametersInfo(SPI_SETWORKAREA, 0, ref rect, WM_SETTINGCHANGE);
}
public static RECT GetWorkArea()
{
var rect = new RECT();
SystemParametersInfo(SPI_GETWORKAREA, 0, ref rect, 0);
return rect;
}
}
}

Categories