728x90
특정항목을 복사하기 위한 기능 Copy Clipboard 처리하는 방법입니다.
Services 폴더를 만들고 Class 를 하나 추가합니다.
ClipboardService.cs
using Microsoft.JSInterop;
namespace Blazor.ClipBoardTest.Services
{
public class ClipboardService
{
private readonly IJSRuntime jsRuntime;
public ClipboardService(IJSRuntime jsRuntime)
{
this.jsRuntime = jsRuntime;
}
public ValueTask<string> ReadTextAsync()
{
return jsRuntime.InvokeAsync<string>("navigator.clipboard.readText");
}
public ValueTask WriteTextAsync(string text)
{
return jsRuntime.InvokeVoidAsync("navigator.clipboard.writeText", text);
}
}
}
Program.cs 에 아래 코드를 추가합니다.
builder.Services.AddScoped<ClipboardService>();
using Blazor.ClipBoardTest.Services;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
namespace Blazor.ClipBoardTest
{
public class Program
{
public static async Task Main(string[] args)
{
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.RootComponents.Add<HeadOutlet>("head::after");
builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
builder.Services.AddScoped<ClipboardService>();
await builder.Build().RunAsync();
}
}
}
화면에서는 아래처럼 처리합니다.
Index.razor
@page "/"
@using Blazor.ClipBoardTest.Services;
@inject ClipboardService ClipboardService;
@inject IJSRuntime JSRuntime
<PageTitle>Copy Clipboard</PageTitle>
<p role="status">GUID: @guid</p>
<button class="btn btn-primary" @onclick="CreateGUID">Carete GUID</button>
<button class="btn btn-primary" @onclick="CopyTextToClipboard">Copy</button>
@code {
private string guid = string.Empty;
private void CreateGUID()
{
guid = Guid.NewGuid().ToString();
}
private async Task CopyTextToClipboard()
{
try
{
await ClipboardService.WriteTextAsync(guid);
}
catch(Exception ex)
{
Console.WriteLine("Clipboard Error " + ex.ToString());
}
}
}
실행결과
[Source]
https://github.com/kei-soft/Blazor.AppTest/tree/master/Blazor.ClipBoardTest
728x90
'C# > Blazor' 카테고리의 다른 글
[Blazor] div 항목 선택할 수 있는 구조로 만들기 (0) | 2023.07.31 |
---|---|
[Blazor] Radzen Blazor Studio 로 CRUD 화면 만들기 (0) | 2023.07.31 |
[Blazor] 에러 - HTTP Error 500.35 - ANCM Multiple In-Process Applications in same Process (0) | 2023.07.23 |
[Blazor] 배포에러 - The specified version of Microsoft.NetCore.App or Microsoft.AspNetCore.App was not found. (0) | 2023.07.22 |
[Blazor] Virtualize 가상화 처리 (0) | 2023.07.20 |