Как сделать так, чтобы iframe оставался активным, когда приложение свернуто?C#

Место общения программистов C#
Anonymous
Как сделать так, чтобы iframe оставался активным, когда приложение свернуто?

Сообщение Anonymous »

Я пишу программу CefSharp.WinForms, которая может автоматически управлять моим веб-сайтом. Оно будет работать нормально, если мое приложение все еще отображается на экране, но если приложение свернуто, оно больше не будет работать, в частности, iframe перестанет воспроизводиться.
Есть ли способ свернуть приложение и по-прежнему воспроизводить iframe с помощью Winforms C #? Потому что мне нужно запустить его на сервере и когда я выйду с пульта, он перестанет работать
Это код в моей форме1:

Код: Выделить всё

using CefSharp;
using CefSharp.WinForms;
using System.Threading.Tasks;
namespace WinFormsAppElearning
{
public partial class Form1 : Form
{
private ChromiumWebBrowser browser;
private bool isLoginAttempted = false;
private string userId = "defaultUserId";
private bool isRunningInBackground = false;
public Form1(string[] args)
{
InitializeComponent();
this.Resize += new EventHandler(Form1_Resize);
}
private void Form1_Resize(object sender, EventArgs e)
{
if (this.WindowState == FormWindowState.Minimized && !isRunningInBackground)
{
browser.Focus();
isRunningInBackground = true;

Task.Run(() =>
{
while (this.WindowState == FormWindowState.Minimized)
{
CheckProgressBar();
Thread.Sleep(1000);
}

isRunningInBackground = false;
});
}
}

private void InitializeChromium()
{
if (!(Cef.IsInitialized ?? false))
{
var settings = new CefSettings
{
WindowlessRenderingEnabled = true,
PersistSessionCookies = true
};

settings.PersistSessionCookies = true;
userId = txtUsername.Text;
string cachePath = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Elearning", "Cache_" + userId);
settings.RootCachePath = cachePath;

// Uncomment for remote debugging
// settings.RemoteDebuggingPort = 8088;

Cef.Initialize(settings);
}
this.FormBorderStyle = FormBorderStyle.Sizable;
this.WindowState = FormWindowState.Maximized;
this.Bounds = Screen.PrimaryScreen.Bounds;

browser = new ChromiumWebBrowser("http://example.com/login")
{
Dock = DockStyle.Fill
};
this.Controls.Add(browser);
browser.IsBrowserInitializedChanged += OnBrowserInitialized;

browser.LoadingStateChanged += OnLoadingStateChanged;
}

private void OnBrowserInitialized(object sender, EventArgs e)
{
if (browser.IsBrowserInitialized)
{
// Uncomment to show DevTools
// browser.ShowDevTools();

// browser.ExecuteScriptAsync("console.log('Browser Initialized');");
}
}

private void OnLoadingStateChanged(object sender, LoadingStateChangedEventArgs e)
{
if (!e.IsLoading)
{
Invoke(new Action(() =>
{
if (browser.Address.Contains("scorm/player.php"))
{
txtUsername.Visible = false;
txtPassword.Visible = false;
btnLogin.Visible = false;
CheckProgressBar();
}
else
{
CheckForLogin();
}
}));
}
}

private void btnLogin_Click(object sender, EventArgs e)
{
string username = txtUsername.Text;
string password = txtPassword.Text;

if (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password))
{
MessageBox.Show("Check username and password");
return;
}

InitializeChromium();
browser.Load("http://example.com/login");
}

private void CheckForLogin()
{
if (!isLoginAttempted)
{
string username = txtUsername.Text;
string password = txtPassword.Text;
if (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password))
{
return;
}
// Inject script to fill username and password, then submit the form
browser.ExecuteScriptAsync($"document.getElementById('username').value = '{username}';");
browser.ExecuteScriptAsync($"document.getElementById('password').value = '{password}';");
browser.ExecuteScriptAsync("document.querySelector('button[type=\"submit\"]').click();");
isLoginAttempted = true;
}
else if (!browser.Address.Contains("/login"))
{
browser.Load("http://example.com/mod/scorm/player.php?a=21&currentorg=RSLBYTyDkzj5W_organization&scoid=67");
isLoginAttempted = false;
}
}

private void OnJavascriptMessageReceived(object sender, JavascriptMessageReceivedEventArgs e)
{
string currentUrl = e.Message.ToString();
MessageBox.Show(currentUrl);

this.Invoke(new Action(() =>
{
this.Text += currentUrl;
}));
}

private bool isPlayButtonClicked = false;

private async void CheckProgressBar()
{
string currentUrl = browser.Address;
if (currentUrl == "http://example.com/mod/scorm/player.php?a=21&currentorg=RSLBYTyDkzj5W_organization&scoid=67")
{
if (this.InvokeRequired)
{
this.Invoke((MethodInvoker)delegate
{
btnLab.Visible = true;
});
}
else
{
btnLab.Visible = true;
}
btnLab.Text = "Text";
}
else if (currentUrl == "http://example.com/mod/scorm/player.php?a=22&currentorg=WlfhdtXvGehiY_organization&scoid=70")
{
if (this.InvokeRequired)
{
this.Invoke((MethodInvoker)delegate
{
btnLab.Visible = true;
});
}
else
{
btnLab.Visible = true;
}
btnLab.Text = "Text";
}
else
{
if (this.InvokeRequired)
{
this.Invoke((MethodInvoker)delegate
{
btnLab.Visible = true;
});
}
else
{
btnLab.Visible = true;
}
btnLab.Text = "TEXT";
}

string script2 = @"
function checkProgressBar() {
return new Promise(function(resolve) {
let attempt = 0;
const maxAttempts = Number.MAX_SAFE_INTEGER;
let checkInterval = 1000;

function check() {
const iframe = document.getElementById('scorm_object');
if (!iframe) {
attempt++;
if (attempt >= maxAttempts) {
resolve('Unable to find iframe after multiple attempts.');
return;
}
setTimeout(check, checkInterval);
return;
}

const innerDoc = iframe.contentDocument || iframe.contentWindow.document;
const progressLabel = innerDoc.querySelector('.progressbar__label');
const timeLabel = innerDoc.querySelector('.progressbar__label_type_time');
const preloader = innerDoc.querySelector('.preloader');

if (preloader &&  preloader.style.display !== 'none') {
resolve('Session has expired!');
return;
}

let totalProgresscheck = 10;

if (progressLabel) {
const progressValue = progressLabel.getAttribute('aria-label');
if (progressValue) {
const [completedProgress, totalProgress] = progressValue.trim().split(' / ');

if (timeLabel) {
const timeValue = timeLabel.getAttribute('aria-label');
if (timeValue) {
const [completedTime, totalTime] = timeValue.trim().split(' / ');

totalProgresscheck = totalTime;
console.log(completedProgress,totalProgress,completedTime,totalTime);
if (completedProgress !== totalProgress && completedTime === totalTime) {
setTimeout(1000);
const nextButton = innerDoc.querySelector('.universal-control-panel__button_next');
const playButton = innerDoc.querySelector('.universal-control-panel__button_play-pause');

console.log(playButton);
if (nextButton) {
if(playButton.getAttribute('aria-pressed') === 'false')
{
nextButton.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, cancelable: true }));
nextButton.dispatchEvent(new MouseEvent('mouseup', { bubbles: true, cancelable: true }));
}
}
setTimeout(3000);
} else if (completedProgress == totalProgress && completedTime === totalTime) {
setTimeout(3000);
resolve('Next');

}
}
}
}
}

if (totalProgresscheck) {
let totalSeconds;
if (!isNaN(totalProgresscheck)) {
totalSeconds = parseInt(totalProgresscheck, 10);
} else {
const [minutes, seconds] = totalProgresscheck.split(':').map(Number);
totalSeconds = (minutes * 60) + seconds;
}

checkInterval = totalSeconds / 10;
console.log(""Check interval (seconds):"", checkInterval);
} else {
console.warn(""Invalid totalProgress value:"", totalProgress);
}

attempt++;
if (attempt >= maxAttempts) {
resolve('Session has expired!');
return;
}
setTimeout(check, checkInterval * 1000);
}
check();
});
}

checkProgressBar();

";

if (browser != null && !browser.IsDisposed && browser.IsBrowserInitialized)
{
var resultProgress = await browser.EvaluateScriptAsync(script2);
if (resultProgress.Success)
{
if (resultProgress.Result != null)
{
string resultMessage = resultProgress.Result.ToString();
if (resultMessage.Contains("Session has expired!"))
{
MessageBox.Show(this, resultMessage, "Notification", MessageBoxButtons.OK, MessageBoxIcon.Warning);
Application.Restart();
}
else if (resultMessage.Contains("Next"))
{
nextSlide();
}
}
}
}
}
private void nextSlide()
{
if (browser != null && !browser.IsDisposed &&  browser.IsBrowserInitialized)
{
browser.ExecuteScriptAsync("document.querySelector('.universal-control-panel__button_next').click();");
}
}
}
}
и я также пытался использовать:
WindowlessRenderingEnabled = true;
но не эффективно
Кто-нибудь, пожалуйста, помогите мне

Подробнее здесь: https://stackoverflow.com/questions/790 ... -minimized

Вернуться в «C#»