B4J Tutorial [Server] Screen Capture & FTP

This code is based on Erel's Screen Capture tutorial - https://www.b4x.com/android/forum/threads/server-screen-capture-server.37292/#content

Using the jAWTRobot lib for a simple screen capture, and Net lib for FTP functions, you can use this code to "silently" run a B4J server in the background, then send screen shots as a "timestamped" .png file to an ftp directory, where you can later pick up the image file and scold your employee for playing Scrabble during work hours!

Libs used:
JavaObject v2.05
jAWTRobot v1.40
jCore v4.20
jDateUtils v1.05
jServer v2.51
jNet v1.10

1- In B4J, create a NEW, non-ui console project

2- In the Main module add this:
B4X:
Sub Process_Globals
  Private srvr As Server
End Sub

Sub AppStart (Args() As String)
  srvr.Initialize("")
  srvr.Port = 51042
  srvr.AddHandler("/sshot", "Capture", False)'
  srvr.Start

  StartMessageLoop
End Sub

3- Under [Project] add a new class module called "Capture" and replace default code with this:
B4X:
'Handler class
Sub Class_Globals
   Private c3po As AWTRobot
   Private oFTP As FTP
End Sub

Public Sub Initialize
End Sub

Sub Handle(req As ServletRequest, resp As ServletResponse)
   Try
     Dim strFileName As String = "screenshot-" & DateTime.Now & ".png"
     Dim strCurDir As String  = "./" 'this default to the objects dir of your java app or jar file
 
     'Capture current monitor screen
     c3po.ScreenCurrentRectangleSetAsRightScreen '<- needed since I have multiple monitors
     c3po.ScreenCaptureToFile(strFileName)
       
     Log( File.Exists(strCurDir,strFileName) )
 
     'FTP File to server
     Dim ctm As CustomTrustManager
     ctm.InitializeAcceptAll
     oFTP.Initialize("FTP", "ftp.YourDomain.com", 21, "YourUserHere", "YourPasswordHere")
     oFTP.PassiveMode   = True
     oFTP.UseSSLExplicit = True
     oFTP.SetCustomSSLTrustManager(ctm)
     oFTP.UploadFile(strCurDir, strFileName, False, "/YourSubDirectory/" & strFileName )     
   
     resp.Write("screen shot saved - " & DateUtils.TicksToString(DateTime.Now) )
   Catch
     resp.SendError(500, LastException.Message)
   End Try
End Sub
*(remember to replace strings stating "Your..." with your FTP info!)

4- You can then fire the server from your browser like this(ip addy of your desktop): http://192.168..x.xx:51042/sshot , or you could implement a timer to fire the handler every xxx seconds...

P.S. eventually planning on using MQTT so I can make this call from any browser on the internet, will post an update here when I do, enjoy :)
 
Last edited:
Top