/// <summary> /// One step before saving to a file, checking if the file is already exists /// </summary> /// <param name="filePath">Full file path to be checked if exists</param> /// <returns>Returns the path that was used to save the image, or 'failed' message</returns> public static string saveToFile(string filePath, Snap currentSnap) { if (currentSnap == null) { MessageBox.Show("Please press 'Grab screen' button.", "Nothing to save", MessageBoxButtons.OK, MessageBoxIcon.Information); return null; } if (!isLegalExt(filePath)) { MessageBox.Show("Currently supporting only '.png', '.bmp' or '.jpeg'."); return null; } if (!Directory.GetParent(filePath).Exists) Directory.CreateDirectory(Directory.GetParent(filePath).FullName); if (Settings.Default.Overwrite || !System.IO.File.Exists(filePath)) //If file does not exist - it will be saved normally { if (performSave(filePath, currentSnap)) return filePath; } else //Otherwise if does exist - it will be save with additional of [number] symbol to the filename { if (System.IO.File.Exists(filePath)) //just another check if the file is exist to be sure { int num = 2; string fullFilePath = Path.GetDirectoryName(filePath) + "\\" + Path.GetFileNameWithoutExtension(filePath); string ext = Path.GetExtension(filePath); string tempPath = ""; while (true) //A method for adding/changing number to the real filename { tempPath = fullFilePath + " [" + num + "]" + ext; num++; if (!File.Exists(tempPath)) // checking if the new filename path is exist { if (performSave(tempPath, currentSnap)) return tempPath; break; } } } } //if nothing goes wrong this is an unreachable code.. return null; }
/// <summary> /// Saves IE web page full content to Image reference. /// </summary> public static void grabWeb() { try { lock(SnapLocker) { SHDocVw.WebBrowser m_browser = null; SHDocVw.ShellWindows shellWindows = new SHDocVw.ShellWindowsClass(); //Find first availble browser window. //Application can easily be modified to loop through and capture all open windows. string filename; foreach(SHDocVw.WebBrowser ie in shellWindows) { filename = Path.GetFileNameWithoutExtension(ie.FullName).ToLower(); if(filename.Equals("iexplore")) { m_browser = ie; break; } } if(m_browser == null) { MessageBox.Show("No IE Browser Open.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if(bmp != null) { bmp.Dispose(); bmp = null; } //Assign Browser Document mshtml.IHTMLDocument2 myDoc = (mshtml.IHTMLDocument2)m_browser.Document; mshtml.IHTMLDocument3 doc3 = (mshtml.IHTMLDocument3)myDoc; //URL Location string myLocalLink = myDoc.url; int URLExtraHeight = 0; int URLExtraLeft = 0; //TrimHeight and TrimLeft trims off some captured IE graphics. int trimHeight = 3; int trimLeft = 3; //Use UrlExtra height to carry trimHeight. URLExtraHeight = URLExtraHeight - trimHeight; URLExtraLeft = URLExtraLeft - trimLeft; setAttribute("scroll", 1, myDoc, doc3); //Get Browser Window Height int heightsize = getAttribute("scrollHeight", myDoc, doc3); int widthsize = getAttribute("scrollWidth", myDoc, doc3); //Get Screen Height int screenHeight = getAttribute("clientHeight", myDoc, doc3); int screenWidth = getAttribute("clientWidth", myDoc, doc3); //Get bitmap to hold screen fragment. Bitmap bm = new Bitmap(screenWidth, screenHeight);//, System.Drawing.Imaging.PixelFormat.Format16bppRgb555); //Create a target bitmap to draw into. Bitmap bm2 = new Bitmap(widthsize + URLExtraLeft, heightsize + URLExtraHeight - trimHeight);//, System.Drawing.Imaging.PixelFormat.Format16bppRgb555); Graphics g2 = Graphics.FromImage(bm2); Graphics g = null; IntPtr hdc; Image screenfrag = null; int brwTop = 0; int brwLeft = 0; int myPage = 0; IntPtr myIntptr = (IntPtr)m_browser.HWND; //Get inner browser window. int hwndInt = myIntptr.ToInt32(); IntPtr hwnd = myIntptr; hwnd = GetWindow(hwnd, GW_CHILD); StringBuilder sbc = new StringBuilder(256); //Get Browser "Document" Handle while(hwndInt != 0) { hwndInt = hwnd.ToInt32(); GetClassName(hwndInt, sbc, 256); if(sbc.ToString().IndexOf("Shell DocObject View", 0) > -1) //IE6 { hwnd = FindWindowEx(hwnd, IntPtr.Zero, "Internet Explorer_Server", IntPtr.Zero); break; } if(sbc.ToString().IndexOf("TabWindowClass", 0) > -1) //IE7 { hwnd = FindWindowEx(hwnd, IntPtr.Zero, "Shell DocObject View", IntPtr.Zero); hwnd = FindWindowEx(hwnd, IntPtr.Zero, "Internet Explorer_Server", IntPtr.Zero); break; } if(sbc.ToString().IndexOf("Frame Tab", 0) > -1) // IE8 { hwnd = FindWindowEx(hwnd, IntPtr.Zero, "TabWindowClass", IntPtr.Zero); hwnd = FindWindowEx(hwnd, IntPtr.Zero, "Shell DocObject View", IntPtr.Zero); hwnd = FindWindowEx(hwnd, IntPtr.Zero, "Internet Explorer_Server", IntPtr.Zero); break; } hwnd = GetWindow(hwnd, GW_HWNDNEXT); } //Get Screen Height (for bottom up screen drawing) while((myPage * screenHeight) < heightsize) { setAttribute("scrollTop", (screenHeight - 5) * myPage, myDoc, doc3); ++myPage; } //Rollback the page count by one --myPage; int myPageWidth = 0; while((myPageWidth * screenWidth) < widthsize) { setAttribute("scrollLeft", (screenWidth - 5) * myPageWidth, myDoc, doc3); brwLeft = getAttribute("scrollLeft", myDoc, doc3); for(int i = myPage ; i >= 0 ; --i) { //Shoot visible window g = Graphics.FromImage(bm); hdc = g.GetHdc(); setAttribute("scrollTop", (screenHeight - 5) * i, myDoc, doc3); brwTop = getAttribute("scrollTop", myDoc, doc3); PrintWindow(hwnd, hdc, 0); g.ReleaseHdc(hdc); g.Flush(); screenfrag = Image.FromHbitmap(bm.GetHbitmap()); g2.DrawImage(screenfrag, brwLeft + URLExtraLeft, brwTop + URLExtraHeight); } ++myPageWidth; } snap = new Snap(bm2, GetExt(Settings.Default.Path), DateTime.Now, Settings.Default.AccountID, null); lastSnap = snap; main.refreshPreview(); if(Settings.Default.SaveSnaps) SnapToDB(snap); //insertSnapToDB.RunWorkerAsync(snap); main.updateStatus(); bm.Dispose(); bm2.Dispose(); screenfrag.Dispose(); g.Dispose(); g2.Dispose(); } } catch(Exception ex) { MessageBox.Show("Couldn't grab web page content.\n" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
/// <summary> /// Saving the Bitmap to a file /// </summary> /// <param name="filePath">A path where you want to save the file</param> /// <returns>True If the operation was seccessful, else return false</returns> public static bool performSave(string filePath, Snap currentSnap) { if(currentSnap == null) return false; Image img; if(Settings.Default.SaveDate) img = DrawDateOnImage(currentSnap.BmpAsImage, currentSnap.Date); else img = currentSnap.BmpAsImage; string ext = Path.GetExtension(filePath); switch(ext.ToUpper()) { case ".PNG": img.Save(filePath, ImageFormat.Png); break; case ".BMP": img.Save(filePath, ImageFormat.Bmp); break; case ".JPG": case ".JPEG": img.Save(filePath, ImageFormat.Jpeg); break; default: img.Dispose(); return false; } img.Dispose(); return true; }
/// <summary> /// Save the screen to a Image reference as image /// </summary> /// <returns>If success.</returns> public static bool grabScreen() { if (busyTimer.Enabled) return false; lock (SnapLocker) { busyTimer.Start(); if (bmp != null) { bmp.Dispose(); bmp = null; } short Width, Height; Width = (short)Screen.PrimaryScreen.Bounds.Width; Height = (short)Screen.PrimaryScreen.Bounds.Height; Graphics G; Point Pt = new Point(0, 0); if (!Settings.Default.CustomBounds) bmp = new Bitmap(Width, Height); else { if (grabberSize.Width <= 0) grabberSize.Width = Width; if (grabberSize.Height <= 0) grabberSize.Height = Height; bmp = new Bitmap(grabberSize.Width, grabberSize.Height); Pt = grabberPosition; } G = Graphics.FromImage(bmp); G.CompositingQuality = CompositingQuality.HighQuality; G.CompositingMode = CompositingMode.SourceCopy; G.InterpolationMode = InterpolationMode.HighQualityBilinear; G.CopyFromScreen(Pt.X, Pt.Y, 0, 0, new Size(bmp.Width, bmp.Height)); snap = new Snap(bmp, GetExt(Settings.Default.Path), DateTime.Now, Settings.Default.AccountID, null); G.Dispose(); bmp.Dispose(); if (tempOperation) { try { if (Settings.Default.SaveSnaps) tableAdapterManager.SnapsTableAdapter.InsertSnap(snap.BmpAsByteArray, snap.Date, snap.AccountID, snap.Comment); } catch { } } } return true; }
//can throw exception! /// <summary> /// Grab a snap from DirectX frontBuffer content. /// </summary> /// <returns>If succeed.</returns> public static bool grabDX() { try { bmp = dxGrabber.TakeScreenshot(); //#region for testing only //// First we need to determine the function address for IDirect3DDevice9 //D3D9.Device device; //List<IntPtr> id3dDeviceFunctionAddresses = new List<IntPtr>(); //using (D3D9.Direct3D d3d = new D3D9.Direct3D()) //{ // using (device = new D3D9.Device(d3d, 0, D3D9.DeviceType.Hardware, IntPtr.Zero, D3D9.CreateFlags.HardwareVertexProcessing, new D3D9.PresentParameters() { BackBufferWidth = 1, BackBufferHeight = 1 })) // { // IntPtr realPointer = device.ComPointer; // IntPtr vTable = Marshal.ReadIntPtr(realPointer); // for (int i = 0; i < 119; i++) // id3dDeviceFunctionAddresses.Add(Marshal.ReadIntPtr(vTable, i * IntPtr.Size)); // } //} //return false; //#endregion //if(busyTimer.Enabled) // return false; //lock(SnapLocker) //{ // try // { using (GraphicsPath gp = new GraphicsPath()) { // busyTimer.Start(); // if(bmp != null) // { // bmp.Dispose(); // bmp = null; // } // D3D9.Direct3D direct3d = new SlimDX.Direct3D9.Direct3D(); // D3D9.AdapterInformation adapter = direct3d.Adapters.DefaultAdapter; // D3D9.PresentParameters parameters = new SlimDX.Direct3D9.PresentParameters(); // parameters.BackBufferFormat = adapter.CurrentDisplayMode.Format; // parameters.BackBufferHeight = adapter.CurrentDisplayMode.Height; // parameters.BackBufferWidth = adapter.CurrentDisplayMode.Width; // parameters.Multisample = SlimDX.Direct3D9.MultisampleType.None; // parameters.SwapEffect = SlimDX.Direct3D9.SwapEffect.Discard; // parameters.PresentationInterval = SlimDX.Direct3D9.PresentInterval.Default; // parameters.FullScreenRefreshRateInHertz = 0; // D3D9.Device device = new D3D9.Device(direct3d, adapter.Adapter, D3D9.DeviceType.Hardware, // parameters.DeviceWindowHandle, D3D9.CreateFlags.SoftwareVertexProcessing, parameters); // D3D9.Surface surface = D3D9.Surface.CreateOffscreenPlain(device, adapter.CurrentDisplayMode.Width, // adapter.CurrentDisplayMode.Height, D3D9.Format.A8R8G8B8, D3D9.Pool.SystemMemory); // device.BeginScene(); // device.EndScene(); // //device.GetFrontBufferData(0, surface); // surface = device.GetBackBuffer(0, 0); // D3D9.Surface.ToFile(surface, Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\screenshot.bmp", D3D9.ImageFileFormat.Bmp); // Rectangle region = new Rectangle(0, 0, adapter.CurrentDisplayMode.Width, adapter.CurrentDisplayMode.Height); // bmp = new Bitmap(D3D9.Surface.ToStream(surface, D3D9.ImageFileFormat.Bmp, new Rectangle(region.Left, region.Top, region.Width, region.Height))); // surface.Dispose(); // device.Present(); using (Graphics g = Graphics.FromImage(bmp)) { g.SmoothingMode = SmoothingMode.AntiAlias; System.Drawing.Font font = new System.Drawing.Font(FontFamily.GenericSansSerif, 18); gp.AddString("Rendered using DirectX.", font.FontFamily, (int)font.Style, font.Size, new Point(10, 10), StringFormat.GenericDefault); g.DrawPath(new Pen(Brushes.Black, 5), gp); g.FillPath(Brushes.White, gp); } snap = new Snap(bmp, GetExt(Settings.Default.Path), DateTime.Now, Settings.Default.AccountID, null); bmp.Dispose(); // return true; // } // } // catch // { // return false; // } } return true; } catch { return false; } }
/// <summary> /// Show a 100% image preview. /// </summary> /// <param name="img">The image to be shown.</param> /// <param name="date">Image snapped date.</param> public Preview(Snap snap) { InitializeComponent(); preparingImageBackgroundWorker.RunWorkerAsync(snap); }
/// <summary> /// Show a 100% image preview. /// </summary> /// <param name="img">The image to be shown.</param> /// <param name="date">Image snapped date.</param> public Preview(Image img, DateTime date) { InitializeComponent(); Snap snap = new Snap(img, Program.GetExt(Settings.Default.Path), date, Settings.Default.AccountID, null); preparingImageBackgroundWorker.RunWorkerAsync(snap); }
/// <summary> /// Try to convert any Obect to Snap. /// </summary> /// <param name="Object">The Obect you want to convert.</param> /// <param name="snap">Referance that will get the new Object if it can convert to Snap or null if doesnt.</param> /// <returns>If Obect was converted to Snap.</returns> public static bool tryConvert(object Object, out Snap snap) { try { snap = (Snap)Object; return true; } catch { snap = null; return false; } }